我是使用 jest 进行测试的新手,我一直在研究如何测试给出的这段代码,以显示在调用 registerUser 时调用了 Axios.post。我在网上搜索过,没有可靠的解决方案可以发布。如能提供解决方案,将不胜感激
这是我需要从 authAction.js 测试的功能
export const registerUser = (userData, history) => dispatch => {
axios
.post("/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
我已经试过了,但似乎不起作用。
import * as authActions from './authActions';
import axios from 'axios';
import configureStore from 'redux-mock-store'; //ES6 modules
import thunk from 'redux-thunk';
const middleware = [thunk];
const mockStore = configureStore(middleware);
describe('test register user axios', () => {
it('should give a response of 201 back after it registers user', () => {
var userData = {email: "kamara@fc.come",
name: "Kris Kamara",
password: "adam123",
password2: "adam123"
}
var history = jest.fn();
const initialState = {}
const store = mockStore(initialState)
store.dispatch(authActions.registerUser({userData}, history));
expect(axios).toHaveBeenCalledTimes(1);
});
});
提前致谢。
最佳答案
像这样从函数中返回 Promise
:
export const registerUser = (userData, history) => dispatch => {
return axios // <= return the Promise
.post("/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
...然后你可以这样测试它:
import * as authActions from './authActions';
import axios from 'axios';
describe('registerUser', () => {
let mock;
beforeEach(() => {
mock = jest.spyOn(axios, 'post');
});
afterEach(() => {
mock.mockRestore();
});
it('should register the user and redirect to login', async () => {
const push = jest.fn();
const history = { push };
const dispatch = jest.fn();
mock.mockResolvedValue(); // mock axios.post to resolve
await authActions.registerUser('the user data', history)(dispatch);
expect(mock).toHaveBeenCalledWith('/api/users/register', 'the user data'); // Success!
expect(history.push).toHaveBeenCalledWith('/login'); // Success!
});
});
关于reactjs - 如何使用提供的操作通过模拟 Axios 编写一个 Jest 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455351/