简体   繁体   中英

Mock the return value of an imported function in Typescript with Jest

I have a function, lets call it generateName, which as you've guessed it, generates a name. The problem is that a new name is generated each time time a test is ran.

In one of my tests, I assert that a function is called with an object containing this name. However, the name keeps on changing. I could just check that the object has property name, but I don't really want to do that.

My idea is that I can mock the return value of the generateName function and do something like this

Import { generateName } from ‘libs/generateName’

jest.fn(generateName).mockResolvedValue ( ‘hello’ )

expect ( spy ).toHaveBeenCalledWith ( 
      expect.objectContaining ( {
        name: 'houses',
      } )
)

You can use jest.mock(moduleName, factory, options) to mock libs/generateName module.

Eg generateName.ts :

export async function generateName() {
  const name = Math.random() + '';
  return name;
}

main.ts :

import { generateName } from './generateName';

export function main() {
  return generateName();
}

main.test.ts :

import { main } from './main';
import { generateName } from './generateName';

jest.mock('./generateName', () => {
  return {
    generateName: jest.fn(),
  };
});

describe('61350152', () => {
  it('should pass', async () => {
    (generateName as jest.MockedFunction<typeof generateName>).mockResolvedValueOnce('hello');
    const actual = await main();
    expect(actual).toBe('hello');
  });
});

unit test results with coverage report:

 PASS  stackoverflow/61350152/main.test.ts (28.524s)
  61350152
    ✓ should pass (6ms)

----------|---------|----------|---------|---------|-------------------
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:        31.98s

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