skip to Main Content

I’m working on a product in Typescript that uses some external package (written in JS if it matters) via npm. In the test i’d like to mock only one JS file from that package.

How can i do it with Jest?

package.js:

  "dependencies": {
    ...
    "@company/product": "1.8.0"
    ...

someFile.ts:

import * as sdk from "@company/product";

I’ve tried to mock it as follows:

someFile.spec.ts:

...

const prefs: IPrefs = {
  some_property: -1
};

jest.mock(
  "@company/product/sdk/api/prefs.js",
  (): { Prefs: IPrefs } => {
    return {
      Prefs: prefs
    };
  }
);

The original "prefs.js" file from the external package looks as follows:


import ... // i can see in the failed test stack trace

export let Prefs = {
  ...
};

But it’s clearly not mocking as i can see the stack trace from the original "prefs.js" that comes in the external package.

2

Answers


    • Create a __mocks__ directory adjacent to the node_modules

    • Inside __mocks__, replicate the directory structure of the package you are mocking.

    Inside __mocks__/company/product/sdk/api/prefs.js, define the mock implementation for your function:

    export const someFunction = jest.fn(() => {
      // return;
    });
    

    Here, jest.fn() creates a mock function that you can control in your tests.

    Login or Signup to reply.
  1. import * as sdk from "@company/product";
    
    
    const mockPrefs = {
      some_property: -1
    };
    
    
    jest.mock('@company/product/sdk/api/prefs.js', () => ({
      Prefs: mockPrefs
    }));
    
    // Import the module to test after the mock setup
    import { someFunctionToTest } from './someFile';
    
    describe('Test someFile', () => {
      it('should use the mocked prefs', () => {
        const result = someFunctionToTest();
        expect(result).toEqual(/* expected result based on mockPrefs */);
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search