Jest Error: Cannot set base providers. After Angular v13 upgrade using 'ng test'

Viewed 1818

After upgrading Angular to v 13 when I try to run my tests in the jest environment I have an error:

Cannot set base providers because it has already been called
import 'jest-preset-angular/setup-jest';

Additionally, I configured Jest like it pointed out in this post: https://thymikee.github.io/jest-preset-angular/docs/next/guides/esm-support/ but it does not help me. Need help. How can I fix my tests?

3 Answers

My solution was to remove the setup-jest.ts file, since import 'jest-preset-angular/setup-jest'; is already executed by @angular-builders/jest.

In order to run Jest testing suite using the native ng test command, you had to install the @angular-builders/jest package.

If you take a look at the node_modules/@angular-builders/jest/dist/jest-config/setup.js you will see that the builder is importing jest-preset-angular/setup-jest for you.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("jest-preset-angular/setup-jest");
//# sourceMappingURL=setup.js.map

Now, you probably have a jest.config.js file within your project, and your configuration is likely to have the following property:

A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed.

setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],

Which means that jest will import setup-jest.ts before all your test, now within the setup-jest.ts you will likely have

import 'jest-preset-angular/setup-jest';

This is where you are importing jest-preset-angular/setup-jest twice.

To prevent this, either remove the import from the setup-jest.ts file or the file name from the setupFilesAfterEnv array.

Related