更新到 Jest 26 后模拟损坏
Mocks broken after updating to Jest 26
我刚刚将 react-scripts 更新到 4.0,其中包括 Jest@26 和一些随附的测试包这里是 package.json 差异:
升级后,部分 Jest mocks 开始失效。似乎模拟的 return 值只是未定义?我错过了什么吗?这是失败的模拟之一
import useFetch from "use-http";
jest.mock("use-http", () => ({
__esModule: true,
default: jest.fn()
}));
describe("the user context", () => {
beforeAll(() => {
useFetch.mockReturnValue({
get: async () => Promise.resolve({ foo: 666 }),
response: { ok: true }
});
});
尝试使用 'get' 方法的测试失败并显示:
TypeError: Cannot destructure property 'get' of '(0 , _useHttp.default)(...)' as it is undefined.
另一个不是默认的,不会为一次性模拟导入包:
jest.mock("_hooks", () => ({
useBaseUrls: jest.fn().mockReturnValue({
app: "bar"
})
}));
访问 'app' 属性 的测试抛出 TypeError: Cannot read property 'app' of undefined
Jest 26 将 resetMocks
的默认行为更改为 true,这会在每次测试前重置模拟状态。
您可以通过在 package.json
中禁用 resetMocks
来恢复到之前的行为
"jest": {
"resetMocks": false
}
关于再次更改默认值的讨论目前是他们 Github 上的一个未决问题:https://github.com/facebook/create-react-app/issues/9935
我刚刚将 react-scripts 更新到 4.0,其中包括 Jest@26 和一些随附的测试包这里是 package.json 差异:
升级后,部分 Jest mocks 开始失效。似乎模拟的 return 值只是未定义?我错过了什么吗?这是失败的模拟之一
import useFetch from "use-http";
jest.mock("use-http", () => ({
__esModule: true,
default: jest.fn()
}));
describe("the user context", () => {
beforeAll(() => {
useFetch.mockReturnValue({
get: async () => Promise.resolve({ foo: 666 }),
response: { ok: true }
});
});
尝试使用 'get' 方法的测试失败并显示:
TypeError: Cannot destructure property 'get' of '(0 , _useHttp.default)(...)' as it is undefined.
另一个不是默认的,不会为一次性模拟导入包:
jest.mock("_hooks", () => ({
useBaseUrls: jest.fn().mockReturnValue({
app: "bar"
})
}));
访问 'app' 属性 的测试抛出 TypeError: Cannot read property 'app' of undefined
Jest 26 将 resetMocks
的默认行为更改为 true,这会在每次测试前重置模拟状态。
您可以通过在 package.json
resetMocks
来恢复到之前的行为
"jest": {
"resetMocks": false
}
关于再次更改默认值的讨论目前是他们 Github 上的一个未决问题:https://github.com/facebook/create-react-app/issues/9935