无法使用TypeScript正确模拟函数 [英] Can't not mock a function correctly with typescript

查看:87
本文介绍了无法使用TypeScript正确模拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟genName函数并测试getMessage函数

I want to mock genName function and test getMessage function

moduleA.ts:

const getMessage = (): string => {
  return `Her name is ${genName()}`;
};

function genName(): string {
  return Math.random() > 0.5 ? 'emilie' : 'novaline';
}

export default {
  getMessage,
  genName
}

这是我的测试文件:

import moduleA from '../moduleA';

moduleA.genName = jest.fn(() => 'mrdulin');

describe('mock function', () => {

  it('t-0', () => {
    expect(jest.isMockFunction(moduleA.genName)).toBeTruthy();
    expect(moduleA.genName()).toBe('mrdulin');
  });

  it('t-0.5', () => {
    expect(jest.isMockFunction(moduleA.genName)).toBeTruthy();
  });

  it('t-1', () => {

    expect(moduleA.getMessage()).toBe('Her name is emilie');
    expect(moduleA.genName).toHaveBeenCalled()


  });

});

但似乎无法模拟genName函数成功:

but it seems not mock genName function success:

 FAIL  jest-examples/__test__/mock-function-0.spec.ts
  ● mock function › t-1

    expect(received).toBe(expected)

    Expected value to be (using ===):
      "Her name is emilie"
    Received:
      "Her name is novaline"

      at Object.it (jest-examples/__test__/mock-function-0.spec.ts:18:34)
      at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
      at process._tickCallback (internal/process/next_tick.js:109:7)

  mock function
    ✓ t-0 (3ms)
    ✓ t-0.5
    ✕ t-1 (14ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 2 passed, 3 total
Snapshots:   0 total
Time:        0.152s, estimated 1s
Ran all test suites related to changed files.

但是我确定moduleA.genName函数已被调用.

But I am sure the moduleA.genName function has been called.

 PASS  jest-examples/__test__/mock-function-0.spec.ts
  mock function
    ✓ t-0 (2ms)
    ✓ t-0.5 (1ms)
    ✓ t-1 (1ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        0.148s, estimated 1s
Ran all test suites related to changed files.

推荐答案

如果您在上面调整了一些代码,它将起作用.更改后,您将使用 exportFunctions.genName()

If you adjust a little of your code above, it will work. Instead of calling genName() directly, after the change, you will use exportFunctions.genName()

const getMessage = (): string => {
  return `Her name is ${exportFunctions.genName()}`;
};

function genName(): string {
  return Math.random() > 0.5 ? 'emilie' : 'novaline';
}

const exportFunctions = {
  getMessage,
  genName
}

export default exportFunctions;

这篇关于无法使用TypeScript正确模拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆