【发布时间】:2017-05-26 16:32:20
【问题描述】:
我有一个 TypeScript 模块(应该无关紧要,因为我认为这也会影响 JS)并且我正在尝试测试我拥有的模块。该模块从外部文件中导入大量数据,并根据 a 变量选择应该返回哪些数据。
我正在尝试运行一些测试来更新该变量,重新require 模块并在一个文件中运行进一步的测试。但我的问题是文件的require 只运行一次。我猜它正在被缓存。是否可以告诉 Jest 的 require 函数不要缓存或在测试之间清除缓存?
这是我想要实现的一些精简代码:
模块.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 中的代码只运行一次。
【问题讨论】:
标签: javascript typescript jestjs