簡體   English   中英

在 Jest 中模擬出口

[英]Mocking exported exports in Jest

我有一個問題,如果我export * from submodule (使用 ES6 模塊語法和 babel),我無法從入口點使用Jest mock子模塊函數。 我想知道有沒有人可以幫忙...

例如給出這個結構:

+ __tests__
|    |- index.js
+ greeter
|    |- index.js
|    |- submodule.js
|- index.js

而這段代碼:

index.js

import { sayHello } from "./greeter";

export const greet = (name) => sayHello(name);

greeter/index.js

export * from "./submodule.js";

greeter/submodule.js

export const sayHello = (name) => console.log(`Hello, ${name}`);

__tests__/index.js

import { greet } from "../index";
import * as greeter from "../greeter";

describe("greet", () => {
    it("Should delegate the call to greeter.sayHello", () => {
        const name = "John";

        greet(name);
    });
});

這一切正常,當測試運行時它通過了。 Hello, John按預期打印到控制台。 對我來說值得的優點是index.js完全不知道greeter模塊的結構,所以我可以重構和重構該代碼而不必擔心我的消費者。

當我嘗試模擬greeter.sayHello,摩擦就來了……

__tests__/index.js

import { greet } from "../index.js";
import * as greeter from "../greeter";

greeter.sayHello = jest.fn();

describe("greet", () => {
    it("Should delegate the call to greeter.sayHello", () => {
        const name = "John";

        greet(name);

        expect(greeter.sayHello).toHaveBeenCalledWith(name);
    });
});

現在,而不是按預期通過測試 - 我收到一個錯誤:

Test suite failed to run

TypeError: Cannot set property sayHello of [object Object] which only has a getter
...(stack trace)

__tests__/index.js中的__tests__/index.jsimport更改為:

import * as greeter from "../greeter/submodule";

使測試通過,但將耦合放回我的測試代碼中。

還有其他方法嗎?

為了在要測試的文件上模擬導入的方法,您需要確保在導入文件(index.js)之前模擬已運行,如下所示:

// import { greet } from "../index.js";   =====> Import on each test case(it)
// import * as greeter from "../greeter"; =====> Mock on each test case(it)

// greeter.sayHello = jest.fn(); =====> Would be not good to do this, it will mess with the entire import and this jest.fn will be share across your tests making it gives you false positives.

describe("greet", () => {
    it("Should delegate the call to greeter.sayHello", () => {
        const name = "John";

        jest.mock('../greeter', () => ({ sayHello: jest.fn() })); // here you mock the import, remember it needs to be before you require your index.js

        const greet = require('../index.js').greet; // require after the mock

        greet(name);

        expect(greeter.sayHello).toHaveBeenCalledWith(name);
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM