Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if external component method is called in jest

Tags:

jestjs

enzyme

I am using jest and enzyme for unit testing. Below is my index.js file. I need to test openNotification and uploadErrorNotification function of the file. However, only uploadErrorNotification function is exported. So, How do I test both the functions.

Also, I don't want to use any other libray except jest and enzyme.

//index.js
import {
      notification
    } from 'antd';

    const openNotification = (message, description, className) => {
      notification.open({
        key: 'upload-template',
        message,
        description,
        placement: "bottomRight",
        duration: null,
      });
    };

    const uploadErrorNotification = (uploadFailedText, errorMsg) => {
      openNotification(uploadFailedText, errorMsg, 'error');
    };

    export {
      uploadErrorNotification
    }

This is my test file:

//test.js

import { uploadErrorNotification } from '../index.js

jest.mock('notification', () => ({ open: () => jest.fn() })); // was trying this but I couldn't understand how it will work

describe('Notification validation functions testing', () => {
  uploadErrorNotification('Upload failed', 'Something went wrong.');
  expect("openNotification").toHaveBeenCalledTimes(1); // want to do something like this
});
like image 355
Jagrati Avatar asked Dec 21 '25 00:12

Jagrati


1 Answers

You have to mock the external depenency:

first mock antd so that notification.open is a spy

jest.mock('antd', () => ({notification: open: {jest.fn()}}))

Then import the module into your test

import { notification  } from 'antd';

Know you can use it like this:

expect(notification.open).toHaveBeenCalledTimes(1);
like image 133
Andreas Köberle Avatar answered Dec 24 '25 11:12

Andreas Köberle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!