不能使用typescript正确模拟函数

时间:2017-05-25 10:27:39

标签: jestjs

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

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功能成功:

 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函数。

 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.

2 个答案:

答案 0 :(得分:0)

我假设您想要模拟它Math.random调用的原因。为什么不嘲笑它:

Math.random = () => 0 
expect(moduleA.getMessage()).toBe('Her name is novaline')
Math.random = () => 1 
expect(moduleA.getMessage()).toBe('Her name is emilie')

当测试在沙箱中运行时,也无法干扰任何其他测试

答案 1 :(得分:0)

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

,而不是直接调用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;