'How to configure Jest v28 with Typescript properly?
When working with TypeScript and Jest v28, how to consume types properly?
The way I used to use it prior to version 28 was like this. In an empty folder set up the following:
> npm init -y
> npm i -D typescript jest@27 @types/jest@27 ts-jest@27
> npx tsc --init
Add a jest.config.js like:
module.exports = {
preset: "ts-jest",
};
And then a test addition.spec.ts like:
describe("addition", () => {
it("should work", () => {
expect(1 + 1).toBe(2);
});
});
npx jest will now run smoothly and we have one green test.
If we install version 28 of jest and ts-jest instead, there are no types matching that version. The latest version is at 27.
Therefore we can only replace the npm install command with:
> npm i -D typescript jest@28 ts-jest@28 (This my assumption, I might be wrong. Perhaps jest@28 and @types/jest@27 are compatible?)
Now if we run the same setup for everything else specified above we would get this error Cannot find name 'describe'. Do you need to install type definitions for a test runner? because no types can be found for describe, it and expect.
That is not very surprising since we haven't installed any types and it seems like TS includes them by default since they live in node_modules/@types. What we can do is to add an explicit import inside our spec file like since Jest themselves includes types (and has done for earlier versions as well it seems like):
import { describe, it, expect } from "@jest/globals";
describe("addition", () => {
it("should work", () => {
expect(1 + 1).toBe(2);
});
});
Thats is a viable solution I guess. Most of all it makes more sense to use existing types from the original project.
But what if I want to avoid making that explicit import in all my spec files? This become even more important if I want to upgrade an existing project from earlier Jest version to latest version 28.
I have attempted to include my types in a "global fashion" by experimenting with typeRoots inside tsconfig.json with no success. That setting sounds like something I would be able to use but I haven't figured out if that is the case.
Also I suspect I might have to configure something inside jest.config.js but same thing there, I don't know what that would be.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
