reactjs - 如何使用提供的操作通过模拟 Axios 来编写一个笑话测试?
问题描述
我是使用 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!
});
});
推荐阅读
- r - 在 dplyr 中使用 {{}} 调用自定义函数
- terraform - 如何暂时静音 terraform 警告
- python-3.x - IndexError:只有整数、切片(`:`)、省略号(`...`)、...是索引中 3 个参数的有效索引
- python - 在 Python 中获取列表元素的所有可能的组合排列
- transactions - Spring Boot 一笔交易多回购
- reactjs - 找不到 react-redux 上下文值;请确保组件包装在 Provider 中
- javascript - Cordova 在后台运行功能
- python - 图像处理后的视频流从服务器到 Web 客户端
- javascript - 如果值发生变化,如何更改字体颜色?
- php - 如何评估字符串变量中的 php 代码?