如何使用 Jest 和 Typescript 模拟类的静态字段



我正在编写依赖于第三方库的Typescript。该库有一个带有静态字段的类。我正试图编写一个模拟库的单元测试,但它似乎从未奏效。这里有一个独立的例子:

// Library.ts
// this simulates my third party library
export class Library {
static code: number = -1;
}
// Consumer.ts
// This consumes the Library in a trivial way
import { Library } from "./Library";
export function setCode(newCode: number) {
Library.code = newCode;
}
// Consumer.test.ts
// This tests the Consumer
import { Library } from "./Library";
jest.mock("./Library", () => {
class Library {
static code: number = -11;
}
return { Library };
});
describe("Consumer", () => {
let consumer: typeof import("./Consumer");
beforeEach(() => {
jest.resetModules();
consumer = require("./Consumer");
});
it("should set code properly", () => {
consumer.setCode(3);
expect(Library.code).toEqual(3);
});
});

在我的测试中,在将代码设置为3之后,我希望正在使用模拟库,因此Library.code也应该是3。然而,它却等于模拟工厂中定义的-11。我一定错过了什么,但我不确定是什么。

找到了一个解决方案,即使用模拟变量:

// Consumer.test.ts
// This tests the Consumer
import { Library } from "./Library";
const mockLibrary = class {
static code: number = -11;
};
jest.mock("./Library", () => {
const Library = mockLibrary;
return { Library };
});
describe("Consumer", () => {
let consumer: typeof import("./Consumer");
beforeEach(() => {
jest.resetModules();
consumer = require("./Consumer");
});
it("should set code properly", () => {
consumer.setCode(3);
expect(mockLibrary.code).toEqual(3);
});
});

最新更新