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

问题描述 投票:0回答:1

我正在编写依赖第三方库的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。我一定是漏掉了什么,但我不确定是什么。

typescript unit-testing jest
1个回答
0
投票

想出了一个解决办法,那就是使用模拟变量作为。

// 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);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.