Как издеваться над полем stati c класса с помощью Jest и Typescript - PullRequest
0 голосов
/ 05 мая 2020

Я пишу Typescript, который зависит от сторонней библиотеки. В библиотеке есть класс с полем stati c. Я пытаюсь написать модульный тест, который имитирует библиотеку, но, похоже, он никогда не работает. Вот автономный пример:

// 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, как определено в фиктивной фабрике. Должно быть, я что-то упускаю, но не знаю, что именно.

1 Ответ

0 голосов
/ 06 мая 2020

Выяснили решение, которое заключается в использовании фиктивных переменных как таковых:

// 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);
    });
});
...