繁体   English   中英

手动模拟不适用于 Jest

[英]Manual mock not working in with Jest

有人可以帮我在 Jest 中手动模拟吗? :) 我尝试让 Jest 使用模拟而不是实际模块。

我的测试:

// __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"
}

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

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

在可能的情况下使用babel-jest转换提升模块模拟,因此这将导致模拟模块:

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

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

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

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的方法,这也可以通过ModuleA.getModuleName而不是整个模块来实现。

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

我的测试:

// __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"
}

我想我遵循了文档中有关手动模拟的所有内容,但是也许我在这里忽略了什么? 这是我的结果:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM