简体   繁体   中英

jest mocking a typescript import as dependency

I searched quite a bit for this and the solutions I see seem a bit hacky and not straightforward for what I think should be a fairly straightforward task.

I have the following class

// client.ts
export interface myClient {
  getClient: (customerId: string) => Promise<string>;
}

const impClient = (): myClient => {   

  return {
    getClient: async (customerId: string) => {
     // Implementation
    }
  };
};

export default impClient;

I'm trying to mock this in jest with a default implementation. I tried many approaches including

 jest.mock('./client', () =>
    jest.fn().mockImplementation(() => {
      return () => {
        return {
          getClient: () => {
            return Promise.resolve('abcde');
          }
        };
      };
    })
  );

but none of them seem to work. Can someone please shed some light on this.

Here is the solution:

client.ts :

export interface myClient {
  getClient: (customerId: string) => Promise<string>;
}

const impClient = (): myClient => {
  return {
    getClient: async (customerId: string) => {
      return customerId;
    }
  };
};

export default impClient;

main.ts , the main function use impClient

import impClient from './client';

export function main(customerId) {
  return impClient().getClient(customerId);
}

main.spec.ts :

import { main } from './main';
import impClient from './client';

jest.mock('./client.ts', () => {
  const mockedClient = {
    getClient: jest.fn()
  };
  return jest.fn(() => mockedClient);
});

const client = impClient();

describe('main', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  it('should return client correctly', async () => {
    (client.getClient as jest.MockedFunction<typeof client.getClient>).mockResolvedValueOnce('abcde');
    const customerId = '1';
    const actualValue = await main(customerId);
    expect(actualValue).toBe('abcde');
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/58107885/main.spec.ts (9.342s)
  main
    ✓ should return client correctly (4ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 main.ts  |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.052s

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58107885

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM