Notistack: Question - Not sure how to test the closeSnackbar case

Created on 6 Apr 2020  路  1Comment  路  Source: iamhosseindhv/notistack

image

  const { closeSnackbar } = useSnackbar();
  ...
  const handleOnClick = () => {
    closeSnackbar();
    onClick();
  };

  return (
    <Button
      variant="contained"
      size="small"
      data-test-id="FooterButton"
      disabled={disabled}
      className={style}
      onClick={handleOnClick}
    >
      {icon}
      {label}
    </Button>
  );
import React from 'react';
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
import Button from '@material-ui/core/Button';

// import footerButtonHandleOnClick from 'utils/footerButtonHandleOnClick';

import i18next from '../../config/i18n';
import FooterButton from './FooterButton.component';

jest.mock('notistack', () => ({
  useSnackbar: jest.fn().mockReturnValue({ closeSnackbar: () => { } }),
}));

jest.mock('utils/footerButtonHandleOnClick');

describe('Foote Button', () => {
  let props;

  beforeEach(() => {
    props = {
      i18next,
      label: 'test',
      type: 'positive',
      onClick: () => {},
    };
  });

  it('should simulate FooterButton click', async () => {
    let component;
    await act(async () => {
      component = mount(<FooterButton {...props} />);
      component.update();
      component.find(Button).filter({ 'data-test-id': 'FooterButton' }).simulate('click');
    });

    expect(useSnackbar.closeSnackbar()).toHaveBeenCalled();
  });
});

Most helpful comment

You need to mock the closeSnackbar function, something like this:

const mockCloseSnackbar = jest.fn();
jest.mock('notistack', () => ({
  useSnackbar: jest
    .fn()
    .mockImplementation(() => ({ closeSnackbar: mockCloseSnackbar }))
}));

Then, your assert would be this:

expect(mockCloseSnackbar).toHaveBeenCalled();

>All comments

You need to mock the closeSnackbar function, something like this:

const mockCloseSnackbar = jest.fn();
jest.mock('notistack', () => ({
  useSnackbar: jest
    .fn()
    .mockImplementation(() => ({ closeSnackbar: mockCloseSnackbar }))
}));

Then, your assert would be this:

expect(mockCloseSnackbar).toHaveBeenCalled();

Was this page helpful?
0 / 5 - 0 ratings

Related issues

james-cordeiro picture james-cordeiro  路  6Comments

iamhosseindhv picture iamhosseindhv  路  7Comments

kubalobo picture kubalobo  路  5Comments

iamhosseindhv picture iamhosseindhv  路  8Comments

alexisab picture alexisab  路  5Comments