I have a notfications.js file which I want to write jest tests for. Can someone tell me how to approach the test cases for this.
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;
I read the jest documentation and read about mock functions but wasn't able to figure a lot out. First time trying to write a unit test.
Solution: I was able to do the testing by creating a spy for the store using jest spyOn. My test was:
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();
});
});
Note: Please refer to the answer provided by @slideshowp2 it is a better solution.