Ale*_*dre 7 mocking reactjs jestjs redux
我试图用开玩笑来模仿我的api电话,但由于某种原因它不起作用.我真的不明白为什么.有人有想法吗?
(测试保持调用原始的api调用函数而不是模拟)
我的test.js
import { getStuff } from '../stuff';
import * as api from '../../util/api';
describe('Action getStuff', () => {
it('Should call the API to get stuff.', () => {
api.call = jest.fn();
getStuff('slug')(() => {}, () => {});
expect(api.call).toBeCalled();
jest.unmock('../../util/api.js');
});
});
Run Code Online (Sandbox Code Playgroud)
stuff.js redux动作
import api from '@util/api';
import { STUFF, API } from '../constant';
export const getStuff = slug => (dispatch, getState) => {
const state = getState();
api.call(API.STUFF.GET, (err, body) => {
if (err) {
console.error(err.message);
} else {
dispatch({
type: STUFF.GET,
results: body,
});
}
}, {
params: { slug },
state
});
};
Run Code Online (Sandbox Code Playgroud)
导入是不可变的,所以它不会工作,你应该模拟整个模块。使用__mock__目录或简单地使用:
jest.mock('../../util/api');
const { call } = require('../../util/api');
call.mockImplementation( () => console.log("some api call"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5662 次 |
| 最近记录: |