简体   繁体   English

用 Jest 模拟 Typescript 中导入的 function 的返回值

[英]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.我有一个 function,我们称它为 generateName,正如您所猜到的,它会生成一个名称。 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.在我的一项测试中,我断言使用包含此名称的 object 调用 function。 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.我可以检查 object 是否具有属性名称,但我真的不想这样做。

My idea is that I can mock the return value of the generateName function and do something like this我的想法是我可以模拟 generateName function 的返回值并做这样的事情

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.您可以使用jest.mock(moduleName, factory, options)来模拟libs/generateName模块。

Eg generateName.ts :例如generateName.ts

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

main.ts : main.ts

import { generateName } from './generateName';

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

main.test.ts : 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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