繁体   English   中英

模拟功能调用仅一次

[英]Mock function call only once

我正在尝试检查同一文件中两个功能的实现。 其中一个函数将调用另一个函数,我想检查它是否确实发生。

import * as strings from './strings';

const generateUuidSpy = jest.spyOn(strings, 'generateUuid');

describe('getContextId()', () => {
  it('it should return a string id if given context and number', () => {
    const actual = strings.getContextId('testQueue', 5);
    const expected = 's1-s5';
    expect(typeof actual).toBe('string');
    expect(actual).toEqual(expected);
  });
  it('it should execute generateUuid()', () => {
    strings.getContextId('notTestQueue');
    expect(generateUuidSpy).toHaveBeenCalled();
  });
});

describe('generateUuid()', () => {
  it('it should return a 36 char UUID string', () => {
    generateUuidSpy.mockRestore();
    const actual = strings.generateUuid();
    const expected = /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/;
    expect(actual.length).toBe(36);
    expect(typeof actual).toBe('string');
    expect(expected.test(actual)).toBe(true);
  });
});

但是我得到这个错误:

expect(jest.fn()).toHaveBeenCalled()

    Expected mock function to have been called, but it was not called.

      12 |   it('it should execute generateUuid()', () => {
      13 |     strings.getContextId('notTestQueue');
    > 14 |     expect(generateUuidSpy).toHaveBeenCalled();
         |                             ^
      15 |   });
      16 | });
      17 |

      at Object.toHaveBeenCalled (src/helpers/strings.test.js:14:29)

通过更改strings.js中导出的​​函数以导出其中包含每个函数的类来解决该问题。 然后在测试中,我启动了该类的新实例,并将其用于测试。

暂无
暂无

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

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