我有一个TypeScript模块(应该是无关紧要的,因为我认为这也会影响JS),我正在尝试测试我拥有的模块.模块从外部文件导入大量数据,并根据变量选择应返回哪些数据.
我正在尝试运行一些测试,我更新该变量,重新require
模块并在一个文件中运行进一步的测试.但我的问题是require
该文件只运行一次.我猜它正在被缓存.是否有可能告诉Jest的require
功能不缓存或清除测试之间的缓存?
这是我正在尝试实现的一些剥离代码:
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"
模拟.问题是module.ts中的代码只运行一次.
所以,非常感谢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()
确保我们重新运行模块中的代码.