Вам необходимо использовать 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