Проверка вызовов методов на (приватной / неэкспортированной) функции, видимой rewire - PullRequest
0 голосов
/ 28 января 2019

У меня есть модуль только с одной экспортируемой функцией и несколькими неэкспортированными для поддержания API в чистоте.Я пытаюсь написать модульные тесты, используя jest & require, но получаю следующую ошибку:

Error: expect(jest.fn())[.not].toBeCalledTimes()
    jest.fn() value must be a mock function or spy.
Received:
    function: [Function doMagic]

Как мне заставить jest шпионить за неэкспортированным методом, который был сделан видимым через rewire (или каким-либо другим способом проверить, как часто вызывается метод), если я пытаюсь шпионить, я получаю эту ошибку, несмотря на возможность вызова функции в последнем тесте, как показано ниже: Cannot spy the doMagic property because it is not a function; undefined given instead

Простой пример моего сценария: Например. functions.js

const moreFunctions = require("./moreFunctions");

const theExportedFunction = someNumber => {
  return doMagic(someNumber);
};

function doMagic(someNumber) {
  if (someNumber % 2 === 0) {
    return moreFunctions.getTrue();
  }
  return moreFunctions.getFalse();
}

module.exports = { theExportedFunction };

Другой модуль: moreFunctions.js

const moreFunctions = {
  getTrue: () => true,
  getFalse: () => false
};

module.exports = moreFunctions;

Как я пытаюсь это проверить: functions.test.js

const rewire = require("rewire");

const functions = rewire("./functions");
const moreFunctions = functions.__get__('moreFunctions');

const doMagic = functions.__get__('doMagic');

const getFalse = jest.spyOn(moreFunctions, 'getFalse');
const getTrue = jest.spyOn(moreFunctions, 'getTrue');

describe("testing inner functions ", () => {

  afterEach(() => {
    jest.clearAllMocks();
  });

  test('theExportedFunction calls doMagic with 1 returns false and does not call getTrue', () => {
    const result = functions.theExportedFunction(1);
    console.log('result: ' + result);
    expect(result).toBe(false);

    //expect(doMagic).toBeCalledTimes(1);  // this blows up
    expect(getTrue).toHaveBeenCalledTimes(0);
    expect(getFalse).toHaveBeenCalledTimes(1);
  });

  test('theExportedFunction calls doMagic with 2 returns true and does not call getFalse', () => {
    const result = functions.theExportedFunction(2);
    console.log('result: ' + result);
    expect(result).toBe(true);

    //expect(doMagic).toBeCalledTimes(1); // this blows up
    expect(getTrue).toHaveBeenCalledTimes(1);
    expect(getFalse).toHaveBeenCalledTimes(0);
  });

  // This works!
  test('just testing to see if i can call the doMagic function', () => {
    const result = doMagic(2);
    expect(result).toBe(true);

    expect(getTrue).toHaveBeenCalledTimes(1);
    expect(getFalse).toHaveBeenCalledTimes(0);
  });
});

1 Ответ

0 голосов
/ 28 января 2019

Учитывая ваш код, вы должны быть в состоянии смоделировать все и проверить theExportedFunction следующим образом:

const mockGetTrue = jest.fn().mockReturnValue(true); // this name MUST start with mock prefix
const mockGetFalse = jest.fn().mockReturnValue(false); // this name MUST start with mock prefix
jest.spyOn('my_more_functions_path', () => ({
  getTrue: mockGetTrue,
  getFalse: mockGetFalse
}));
// here import the file you are testing, after the mocks! 
// for example
import {theExportedFunction} from 'my_path';

describe('theExportedFunction', () => {
  it('should call getTrue of moreFunctions', () => {
    theExportedFunction(4);
    expect(mockGetTrue).toHaveBeenCalled();
    expect(mockGetFalse).not.toHaveBeenCalled();
  });


  it('should call getFalse of moreFunctions', () => {
    theExportedFunction(5);
    expect(mockGetFalse).toHaveBeenCalled();
    expect(mockGetTrue).not.toHaveBeenCalled();
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...