4

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
...

1 Answers1

3

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');
  });
});
Flo Schild
  • 5,104
  • 4
  • 40
  • 55
  • The answer didn't work for me, but I changed the place of the `__mocks__` folder to be under `src` folder inside the library and it worked. Also one important note is that the call `jest.mock('@workspace-scope/mylib');` has to be at the top level (outside of `describe`). – Envil Jun 01 '23 at 22:03