我刚刚将 react-scripts 更新到 4.0,其中包括 Jest@26 和一些随附的测试包,这里是 package.json diff:
升级后,一些 Jest 模拟开始失败。似乎模拟的返回值只是未定义?我错过了什么吗?这是失败的模拟之一
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
答案 0 :(得分:12)
Jest 26 将 resetMocks
的默认行为更改为 true,这会在每次测试之前重置模拟状态。
您可以通过在 resetMocks
package.json
来恢复之前的行为
"jest": {
"resetMocks": false
}
重新更改默认设置的讨论目前在他们的 Github 上是一个未解决的问题:https://github.com/facebook/create-react-app/issues/9935