reactjsmonoreponrwl-nxnrwl

ReferenceError: jest is not defined when trying to run tests inside a lib in a nx monorepo


I've been trying to run tests inside a lib from a NX monorepo and it's not working. First it's wasn't finding the types, so I added /// <reference types="@types/jest" /> and It was solved. Then when I ran the test and I got the error: ReferenceError: jest is not defined. Jest is installed in the root of the monorepo, I also tried to install jest for the lib, also dropped the node_modules. Nothing worked for me.

/// <reference types="@types/jest" />

import { handleTokenAuthorization } from '.';

describe('auth funtions', () => {
  it('Should mount and replace url correctly to login screen', () => {
    const url = `${process.env.NX_APP_CLIENT_ID}/authorize?response_type=code&client_id=${process.env.NX_FRONT_URL}&scope=openid+profile&redirect_uri=${process.env.VITE_FRONT_URL}/receive-auth-token`;
    const replaceFn = jest.spyOn(window.location, 'replace');

    handleTokenAuthorization();

    expect(replaceFn).toBeCalledWith(url);
  });
});

enter image description here


Solution

  • I switched vitest by @nrwl/jest:jest, so I added the following config inside the project.json from my lib and the test runner worked fine.

    "test": {
          "executor": "@nrwl/jest:jest",
          "outputs": [
            "{workspaceRoot}/coverage/{projectRoot}"
          ],
          "options": {
            "jestConfig": "libs/util/jest.config.ts",
            "passWithNoTests": true,
            "coverageDirectory": "coverage/libs/util"
          },
          "configurations": {
            "ci": {
              "ci": true,
              "codeCoverage": true
            }
          }
        }