Ложный вызов функции только один раз - PullRequest
0 голосов
/ 22 февраля 2019

Я пытаюсь проверить реализацию двух функций в одном файле.Одна из функций вызовет другую функцию, и я хочу проверить, действительно ли это происходит.

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)

1 Ответ

0 голосов
/ 22 февраля 2019

Решил проблему, изменив экспортируемые функции внутри strings.js, чтобы экспортировать класс с каждой функцией внутри него.Затем в своем тесте я инициировал новый экземпляр класса и использовал его для тестов.

...