本文介绍了手动模拟不适用于Jest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我在Jest中进行手动模拟吗? :)我尝试让Jest使用模拟代替实际模块.

Can somebody help me with manual mocking in Jest, please? :)I try to have Jest use the mock instead of the actual module.

我的测试:

// __tests__/mockTest.js

import ModuleA from "../src/ModuleA"

describe("ModuleA", () => {
    beforeEach(() => {
        jest.mock("../src/ModuleA")
    })

    it("should return the mock name", () => {
        const name = ModuleA.getModuleName()
        expect(name).toBe("mockModuleA")
    })
})

我的代码:

// src/ModuleA.js
export default {
    getModuleName: () => "moduleA"
}

// src/__mocks__/ModuleA.js
export default {
    getModuleName: () => "mockModuleA"
}

我想我遵循了文档所说的所有内容手动模拟,但也许我在这里忽略了一些东西?这是我的结果:

I think I followed everything the documentation says about manual mocks, but perhaps I'm overlooking something here?This is my result:

Expected value to be:
      "mockModuleA"
Received:
      "moduleA"

推荐答案

在可能的情况下,通过babel-jest转换悬挂模块模拟,因此将导致模拟模块:

Module mocks are hoisted when possible with babel-jest transform, so this will result in mocked module:

import ModuleA from "../src/ModuleA"
jest.mock("../src/ModuleA") // hoisted to be evaluated prior to import

如果每个测试基础上都要模拟一个模块,这将不起作用,因为jest.mock驻留在beforeEach函数中.

This won't work if a module should be mocked per test basis, because jest.mock resides in beforeEach function.

在这种情况下,应使用require:

In this case require should be used:

describe("ModuleA", () => {
    beforeEach(() => {
        jest.mock("../src/ModuleA")
    })

    it("should return the mock name", () => {
        const ModuleA = require("../src/ModuleA").default;
        const name = ModuleA.getModuleName()
        expect(name).toBe("mockModuleA")
    })
})

因为它不是导出而是应该模拟的默认导出方法,所以也可以通过模拟ModuleA.getModuleName而不是整个模块来实现.

Since it's not an export but a method in default export that should be mocked, this can also be achieved by mocking ModuleA.getModuleName instead of entire module.

这篇关于手动模拟不适用于Jest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:12