有人可以帮我在 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"
}
我想我遵循了 documentation 的所有内容说到手动模拟,但也许我在这里忽略了一些东西? 这是我的结果:
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
而不是整个模块来实现。
关于javascript - 手动模拟不适用于 Jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694366/