Тестирование вложенных функций в Jest без возврата - PullRequest
0 голосов
/ 27 апреля 2020

У меня есть уведомления. js файл, для которого я хочу написать шутки. Может кто-нибудь сказать мне, как подходить к тестовым случаям для этого.

import { store } from 'react-notifications-component';

/**
 * Helper function to add a notification anywhere.
 * @param {*} title string
 * @param {*} message string
 * @param {*} type  string of success, danger, info, default, warning
 */
const addNotification = (title, message, type) => {
  const options = {
    title,
    message,
    type,
    insert: 'top',
    container: 'top-right',
    animationIn: ['animated', 'fadeIn'],
    animationOut: ['animated', 'fadeOut'],
  };

  store.addNotification({
    ...options,
    dismiss: {
      duration: 5000,
      onScreen: true,
      pauseOnHover: true,
    },
  });
};

export default addNotification;

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

Решение : я смог провести тестирование, создав шпиона для магазина с помощью jest spyOn. Мой тест был:

const params = {
  title: 'test',
  type: 'success',
  message: 'this is a test notification!',
};

describe('addNotification', () => {
  beforeAll(() => {
    jest.spyOn(store, 'addNotification');
  });

  afterAll(() => {
    jest.restoreAllMocks();
  });

  test('calls store.addNotification()', () => {
    addNotification(params.title, params.message, params.type);
    expect(store.addNotification).toHaveBeenCalled();
  });

});

Примечание : Пожалуйста, обратитесь к ответу @ slideshowp2 лучше решение.

1 Ответ

1 голос
/ 28 апреля 2020

Вам необходимо использовать jest.mock (moduleName, factory, options) для макета react-notifications-component пакета. Я добавил опцию { virtual: true }, потому что я не установил этот пакет, просто для демонстрации. Если вы установили этот пакет, вы можете удалить эту опцию.

Например

notifications.js:

import { store } from 'react-notifications-component';

const addNotification = (title, message, type) => {
  const options = {
    title,
    message,
    type,
    insert: 'top',
    container: 'top-right',
    animationIn: ['animated', 'fadeIn'],
    animationOut: ['animated', 'fadeOut'],
  };

  store.addNotification({
    ...options,
    dismiss: {
      duration: 5000,
      onScreen: true,
      pauseOnHover: true,
    },
  });
};

export default addNotification;

notifications.test.js:

import addNotification from './notifications';
import { store } from 'react-notifications-component';

jest.mock(
  'react-notifications-component',
  () => {
    const mStore = {
      addNotification: jest.fn(),
    };
    return { store: mStore };
  },
  { virtual: true },
);

describe('61461299', () => {
  it('should pass', () => {
    const title = 'jest';
    const message = 'unit testing';
    const type = 'ok';
    addNotification(title, message, type);
    expect(store.addNotification).toBeCalledWith({
      title,
      message,
      type,
      insert: 'top',
      container: 'top-right',
      animationIn: ['animated', 'fadeIn'],
      animationOut: ['animated', 'fadeOut'],
      dismiss: {
        duration: 5000,
        onScreen: true,
        pauseOnHover: true,
      },
    });
  });
});

результаты модульного тестирования со 100% покрытием:

 PASS  stackoverflow/61461299/notifications.test.js (11.362s)
  61461299
    ✓ should pass (4ms)

------------------|---------|----------|---------|---------|-------------------
File              | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------------|---------|----------|---------|---------|-------------------
All files         |     100 |      100 |     100 |     100 |                   
 notifications.js |     100 |      100 |     100 |     100 |                   
------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.33s

исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61461299

...