我正在测试调用它的辅助函数apiMiddleware
的callApi
。为了防止调用将发出API调用的实际callApi
,我模拟了该函数。但是,它仍然被调用。
apiMiddleware.js
import axios from 'axios';
export const CALL_API = 'Call API';
export const callApi = (...arg) => {
return axios(...arg)
.then( /*handle success*/ )
.catch( /*handle error*/ );
};
export default store => next => action => {
// determine whether to execute this middleware
const callAPI = action[CALL_API];
if (typeof callAPI === 'undefined') {
return next(action)
}
return callAPI(...callAPI)
.then( /*handle success*/ )
.catch( /*handle error*/ );
}
apiMiddleware.spec.js
import * as apiMiddleware from './apiMiddleware';
const { CALL_API, default: middleware, callApi } = apiMiddleware;
describe('Api Middleware', () => {
const store = {getState: jest.fn()};
const next = jest.fn();
let action;
beforeEach(() => {
// clear the result of the previous calls
next.mockClear();
// action that trigger apiMiddleware
action = {
[CALL_API]: {
// list of properties that change from test to test
}
};
});
it('calls mocked version of `callApi', () => {
const callApi = jest.spyOn(apiMiddleware, 'callApi').mockReturnValue(Promise.resolve());
// error point: middleware() calls the actual `callApi()`
middleware(store)(next)(action);
// assertion
});
});
请忽略callApi
函数的动作属性和参数。我不认为他们是我想要的关注点。
告诉我你是否需要进一步阐述。
jest mocking仅适用于导入的函数。在你的apiMiddleware.js
中,default
函数调用callApi
变量,而不是“导出的”callApi
函数。要使模拟工作,将callApi
移动到自己的模块中,并将import
移动到apiMiddleware.js
好问题!