Search code examples
reactjsjestjsnrwlnomachine-nx

NX React - how to create default mock for library


How do you create manual mock for your libs, which are used by your apps?

I'm trying to follow scope mocking in jest documentation but have no luck.

Example:

my-workspace
├── __mocks__
│   └── @my-workspace/my-lib.ts
├── apps
│   ├── my-app
│       └── index.ts
├── libs
│   ├── my-lib
│       └── index.ts
...

Solution

  • libs in an nx workspace can be imported like regular node_modules thanks to its TS path mapping (check your tsconfig.base.json to see how @workspace-scope/my-lib is being resolved).

    However, your lib is not a node module per say (even if you publish it), and should be mocked using the "user modules" jest pattern instead: https://jestjs.io/docs/manual-mocks#mocking-user-modules

    Move the mock to libs/my-lib/__mocks__/index.ts instead (you can split mocks into several files if you need, just make sure to export whatever you need to mock from the index file) then call jest.mock('@workspace-scope/my-lib'); manually in the spec file where you import your lib function:

    // libs/my-lib/__mocks__/index.ts
    export function foo(): string {
      return 'foo';
    }
    
    // apps/my-app/.../some-test.spec.ts
    import { foo } from '@workspace-scope/my-lib';
    
    // manually mock the user module: make sure the path matches the import above
    jest.mock('@workspace-scope/mylib');
    // --> now when you invoke foo() in this file, jest should invoke "foo" exported from "libs/my-lib/__mocks__/index.ts" instead
    
    describe('test foo', () => {
      test('returns "foo"', () => {
        expect(foo()).toBe('foo');
      });
    });