更新到Jest26后模拟损坏

我刚刚将 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

回答

Jest 26 将默认行为更改resetMocks为 true,这会在每次测试之前重置模拟状态。

您可以通过禁用恢复到以前的行为resetMockspackage.json

  "jest": {
    "resetMocks": false
  }

再次更改默认设置的讨论目前在他们的 Github 上是一个未解决的问题:https : //github.com/facebook/create-react-app/issues/9935


以上是更新到Jest26后模拟损坏的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>