TypeScriptモジュールがあり(これはJSにも影響すると思うので、関係ないはずです)、持っているモジュールをテストしようとしています。モジュールは外部ファイルから大量のデータをインポートし、変数に基づいて返されるデータを選択します。
その変数を更新しrequire
、モジュールを再作成して、1つのファイルでさらにテストを実行するいくつかのテストを実行しようとしています。しかし、私の問題はrequire
、ファイルのが1回しか実行されないことです。キャッシュされていると思います。require
テスト間でキャッシュしないように、またはキャッシュをクリアするようにJestの関数に指示することは可能ですか?
これが私が達成しようとしていることのいくつかのストリップバックコードです:
module.ts
import { getLanguage } from "utils/functions";
import * as messagesEn from "resources/translations/en";
import * as messagesFr from "resources/translations/fr";
// Determine the user's default language.
const language: string = getLanguage();
// Set messages based on the language.
let messages: LocaleMessages = messagesEn.default;
if (languageWithoutRegionCode === "fr") {
messages = messagesFr.default;
}
export { messages, language };
test.ts
import "jest";
// Mock the modules
const messagesEn = { "translation1": "English", "translation2": "Words" };
const messagesFr = { "translation1": "Francais", "translation2": "Mots" };
const getLangTest = jest.fn(() => "te-ST");
const getLangEn = jest.fn(() => "en-GB");
const getLangFr = jest.fn(() => "fr-FR");
jest.mock("resources/translations/en", () => ({"default": messagesEn}));
jest.mock("resources/translations/fr", () => ({"default": messagesFr}));
jest.mock("utils/functions", () => ({
getLanguage: getLangTest
})
);
describe("Localisation initialisation", () => {
it("Sets language", () => {
const localisation = require("./localisation");
expect(getLangTest).toHaveBeenCalled();
expect(localisation.language).toEqual("te-ST");
expect(localisation.messages).toEqual(messagesEn);
});
it("Sets english messages", () => {
// THIS GETS THE MODULE FROM THE CACHE
const localisation = require("./localisation");
expect(getLangEn).toHaveBeenCalled();
expect(localisation.language).toEqual("en-GB");
expect(localisation.messages).toEqual(messagesEn);
});
it("Sets french messages", () => {
// THIS GETS THE MODULE FROM THE CACHE
const localisation = require("./localisation");
expect(getLangFr).toHaveBeenCalled();
expect(localisation.language).toEqual("fr-FR");
expect(localisation.messages).toEqual(messagesFr);
});
});
"utils/functions"
モックを更新する必要があるため、2番目と3番目のテストはとにかく機能しないことを認識しています。問題は、module.tsのコードが1回しか実行されないことです。
だから、DiscordのJestの人々に感謝します。jest.resetModules()
関数を使用して、キャッシュからモジュールを実際にクリアすることができます。
したがって、私のtest.tsファイルは次のようになります。
describe("Localisation initialisation", () => {
beforeEach(() => {
jest.resetModules();
});
it("Sets language", () => {
const localisation = require("./localisation");
// Perform the tests
});
it("Sets english messages", () => {
const localisation = require("./localisation");
// Perform the tests
});
it("Sets french messages", () => {
const localisation = require("./localisation");
// Perform the tests
});
});
のbeforeEach()
呼び出しjest.resetModules()
は、モジュール内のコードを再実行していることを確認します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加