簡體   English   中英

您如何在與 typescript 開玩笑的測試之間重置測試對象?

[英]How do you reset the test subject in between tests in jest with typescript?

我正在使用 typescript 並開玩笑。 我正在嘗試執行一個非常簡單的單元測試,但它總是失敗。 這是我的代碼:

// init.ts
let initialized = false;
let secretName: string;

export function init(name: string) {
    if (initialized) {
        throw new Error("Cannot re-initialize.");
    }

    secretName = name;

    initialized = true;
}

export function getSecret(): string {
    return secretName;
}
// init.test.ts
describe("init", () => {
    async function getTestSubject() {
        return await import("./init");
    }

    it("should set the secret name properly", async () => {
        const init = await getTestSubject();
        init.init("bruce wayne");
        expect(init.getSecret()).toEqual("bruce wayne");
    });

    it("should throw an exception if initialized more than once", async () => {
        const init = await getTestSubject();

        const callInit = function() {
            init.init("bruce wayne");
        };
        callInit();
        expect(callInit).toThrowError("Cannot re-initialize.");
    });
});

由於拋出異常,第二個單元測試失敗。 當調用第一個“callInit()”時,應該是第一次為該單元測試調用 init。 但是,在考慮兩個單元測試時,這是第二次調用它。

我認為通過在每個測試中動態導入測試主題(例如“./init”),我會避免這個問題,因為我最初嘗試在頂部導入 init,如下所示:

import {init, getSecret} from "./init";

關於如何測試這個的任何想法? 我認為這是一個非常基本的測試用例,所以要么開玩笑有很大的限制,要么我只是遺漏了一些明顯的東西......

謝謝!

我可以通過在beforeEach() jest.resetModules()來使其工作,以便在每次測試之前重置模塊名稱空間。

let initModule

beforeEach(() => {
  jest.resetModules()
  initModule = require('./init')
})

it('should set the secret name properly', () => {
  initModule.init('bruce wayne')
  expect(initModule.getSecret()).toEqual('bruce wayne')
})

it('should throw an exception if initialized more than once', () => {
  const callInit = () => initModule.init('bruce wayne')
  callInit()
  expect(callInit).toThrowError('Cannot re-initialize.')
})

您是正確的,這里需要內聯導入其他模塊,因為使用標准 ES6 導入無法完成模塊命名空間的重置。 不過,在上面的示例中,我使用了我認為更簡單的require()方法來執行此操作。

如果您正在使用 typescript 並且仍然希望強烈鍵入initModule ,您仍然可以使用標准 ES6 導入來導入它以獲取類型。

import * as InitModule from './init'

let initModule: typeof InitModule

暫無
暫無

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

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