Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Last active December 19, 2024 08:05
Show Gist options
  • Save LayZeeDK/4ade2b244e1f0e7bd06d5dcf6d71e898 to your computer and use it in GitHub Desktop.
Save LayZeeDK/4ade2b244e1f0e7bd06d5dcf6d71e898 to your computer and use it in GitHub Desktop.
Resolve Nx generator unit test issues in Nx 18/19.
/// <reference types="jest" />
import { createProjectGraphAsync } from '@nx/devkit';
/**
* Resolve `TypeError: performance.mark is not a function`.
*
* @see https://github.com/nrwl/nx/issues/23435#issuecomment-2127183725
*/
const performanceMock: Performance = {
...performance,
mark: jest.fn(),
measure: jest.fn(),
};
Object.defineProperties(globalThis, {
performance: { value: performanceMock },
});
jest.doMock('perf_hooks', () => ({
...jest.requireActual('perf_hooks'),
performance: performanceMock,
}));
jest.doMock('node:perf_hooks', () => ({
...jest.requireActual('node:perf_hooks'),
performance: performanceMock,
}));
/**
* Resolve `LoadPluginError: Could not load plugin node_modules/nx/src/plugins/project-json/build-nodes/package-json-next-to-project-json`.
*
* When `createProjectGraphAsync` is called during tests, if its not
* mocked, it will return the actual Nx workspace's project graph. We
* don't want any unit tests to depend on the structure of the actual
* Nx workspace, so we mock it to return an empty project graph.
*
* @see https://github.com/nrwl/nx/issues/23435
* @see https://github.com/nrwl/nx/blob/0392a67a70e26ddf19a9fffc3131370c427aae0b/scripts/unit-test-setup.js
*/
jest.doMock('@nx/devkit', () => ({
...jest.requireActual('@nx/devkit'),
createProjectGraphAsync: jest.fn().mockImplementation(
(): ReturnType<typeof createProjectGraphAsync> =>
Promise.resolve({
nodes: {},
dependencies: {},
})
),
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment