我已经为Axios创建了一个工作Mock:
// __mocks__/axios.js
// Based on https://jestjs.io/docs/manual-mocks
const axios = jest.createMockFromModule("axios");
const log = console.log.bind(console);
axios.create = () => {
log(`Running axios.create`);
return {
get: () => {
log(`Running get`);
return {
status: 500,
statusText: "Internal Server Error",
body: {
onFire: "Mock API response from mock axios module",
},
};
},
};
};
module.exports = axios;
这在我的测试中工作得很好-模拟是自动加载的,'抛出错误'测试工作:
describe(`getLatestPrice`, () => {
it(`throws an error when the response is bad`, async () => {
expect(() => {
log(`Should throw`);
return getLatestPrice(assetCode);
}).toThrow();
});
it(`gets a single price by stream code`, async () => {
// Disabling the mock isn't working
jest.unmock("axios");
const price = await getLatestPrice(assetCode);
log(`price`, price);
expect(price).toEqual({
...
});
});
})
然而第二个测试——调用jest.unmock()
——仍然使用模拟库。
如何禁用单个测试的mock ?
更新:阅读https://github.com/facebook/jest/issues/2649我还尝试使用requireActual()
覆盖模拟:
const actualAxios = jest.requireActual("axios");
const mockAxios = require("axios");
mockAxios.create = actualAxios.create;
但是对axios.create()
的调用仍然涉及mock。
我在模拟useSelector时遇到了类似的问题,我希望它在其他测试中正常运行。最终唯一有效的方法是用实际的useSelector来模拟模拟的useSelector。所以首先要确保有办法访问实际的模块:
import {useSelector as actualUseSelector} from "react-redux"
import {useSelector} from "react-redux";
那么我的嘲讽就完成了
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn()
}));
需要修改redux状态的测试
useSelector.mockImplementation(callback => {
return callback({
sliceA: {...initialStateSliceA},
sliceB: {...initialStateSliceB},
sliceC: {...initialStateSliceC, importantData: [{d: 1}, {d: 2}]}
})
})
然后在测试中,我需要原始的useSelector
useSelector.mockImplementation(()=>actualUseSelector)
成功了!
实际上,上面的解决方案并没有像预期的那样工作,它在一个情况下工作,但由于错误的原因。它仍然是一个模拟函数(仔细想想,这是有道理的)。但最终我找到了一个可行的解决方案:
你必须重新创建整个redux:
const actualRedux = jest.requireActual('react-redux')
,然后用实际的useSelector或useDispatch模拟它们:
useSelector.mockImplementation(actualRedux.useSelector)
useDispatch.mockImplementation(actualRedux.useDispatch)
模拟的类型是全局模拟。所有使用"公理"的测试实例本质上是硬连接到返回500响应的。为了实现每个测试行为,您将需要模拟"axios"。局部在测试中。然后,您可以在每个测试中修复模拟,使其以您期望的方式响应。