'Retrieve changed typings after mocking an external dependency in Jest
I use many Typescript types that are defined using constant arrays and objects. Consider an example in which a type is defined from an array:
FruitKinds.ts
export const FRUIT_KINDS = ["apple", "orange", "banana"] as const;
export type FruitKind = typeof FRUIT_KINDS[number];
I then import this type for use inside of a class:
Fruit.ts
import { FruitKind } from "./FruitKinds";
class Fruit {
kind: FruitKind;
constructor(kind: FruitKind) {
this.kind = kind;
}
get formattedKind() {
return `My Fruit: ${this.kind}`;
}
}
export default Fruit;
When it's time to unit test the class, I know that there will many changes to FRUIT_KINDS throughout development so I need to manually mock its values:
Fruit.test.ts
import Fruit from "./Fruit";
jest.mock("./fruitKinds", () => {
const originalModule = jest.requireActual("./fruitKinds");
return {
__esModule: true,
...originalModule,
FRUIT_KINDS: ["cherry", "grapes"],
};
});
it("should return a string that includes the fruit kind", () => {
const fruit = new Fruit("cherry");
expect(fruit.formattedKind).toBe("My Fruit: cherry");
});
In the test, the Fruit class retains its original typings and Typescript complains that "cherry" is not assignable to a type of "apple" | "orange | "banana". How would I go about retrieving a Fruit class that includes the typings that changed after mocking ./FruitKinds?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
