Notistack: Test notistack through Jest Enzyme

Created on 9 Dec 2019  ·  8Comments  ·  Source: iamhosseindhv/notistack

$ yarn test

 FAIL  src/__tests__/test.tsx (9.388s)
  ● Console

    console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Uncaught [TypeError: Cannot read property 'enqueueSnackbar' of undefined]

...

  ● MainComponent › renders

    TypeError: Cannot read property 'enqueueSnackbar' of undefined

      525 | 
    > 526 |   const { enqueueSnackbar, closeSnackbar } = useSnackbar()
          |                                              ^

src/__tests__/test.tsx:

import React from 'react'
import Enzyme, { shallow, mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import { App } from '../App'
import { MainComponent } from '../components/MainComponent'

Enzyme.configure({ adapter: new Adapter() })

describe('App', () => {
  it('renders', () => {
    const wrap = shallow(<App />)
    expect(wrap.exists()).toBe(true)
  })
})

describe('MainComponent', () => {
  it('renders', () => {
    const wrap = mount(
      <MainComponent
        prop1='prop1'
        prop2='prop2'
      />
    )
    expect(wrap.exists()).toBe(true)
  })
})

src/index.tsx:

import ReactDOM from 'react-dom'
import React from 'react'
import { App } from './App'
import { SnackbarProvider } from 'notistack'

ReactDOM.render(
  <SnackbarProvider maxSnack={5} dense={false}>
    <App />
  </SnackbarProvider>,
  document.querySelector('#app')
)

src/compoments/MainComponent.tsx:

...
import { useSnackbar } from 'notistack'
...
const { enqueueSnackbar, closeSnackbar } = useSnackbar()

Most helpful comment

Have this issue too using testing-library. This workaround works but is really ugly:

import notistack from 'notistack';

jest.mock('notistack', () => ({
  useSnackbar: jest.fn()
}));
const enqueueSnackbar = jest.fn();
jest.spyOn(notistack, 'useSnackbar').mockImplementation(() => {return {enqueueSnackbar}});
...
expect(enqueueSnackbar).toBeCalledWith("Order submitted", {"variant": "success"});

All 8 comments

Have this issue too using testing-library. This workaround works but is really ugly:

import notistack from 'notistack';

jest.mock('notistack', () => ({
  useSnackbar: jest.fn()
}));
const enqueueSnackbar = jest.fn();
jest.spyOn(notistack, 'useSnackbar').mockImplementation(() => {return {enqueueSnackbar}});
...
expect(enqueueSnackbar).toBeCalledWith("Order submitted", {"variant": "success"});

Thanks @kormbrek-rally
I changed the title to have some keywords, so people in future can hopefully find this issue using search.

Have this issue too using testing-library. This workaround works but is really ugly:

import notistack from 'notistack';

jest.mock('notistack', () => ({
  useSnackbar: jest.fn()
}));
const enqueueSnackbar = jest.fn();
jest.spyOn(notistack, 'useSnackbar').mockImplementation(() => {return {enqueueSnackbar}});
...
expect(enqueueSnackbar).toBeCalledWith("Order submitted", {"variant": "success"});

This doesn't work for me. My code:

import notistack from "notistack";

jest.mock("notistack", () => ({
  useSnackbar: jest.fn(),
}));

const closeSnackbar = jest.fn();
jest.spyOn(notistack, "useSnackbar").mockImplementation(() => {
  return { closeSnackbar };
});

The error I get: "Cannot spyOn on a primitive value; undefined given"

In my case, I needed to wrap the component around SnackbarProvider.

// index.test.js

import { SnackbarProvider } from 'notistack';

const wrap = mount(
    <SnackbarProvider>
        <MainComponent
            prop1='prop1'
            prop2='prop2'
        />
    </SnackbarProvider>
)

That's what worked for me:

const mockEnqueue = jest.fn();

jest.mock('notistack', () => ({
  ...jest.requireActual('notistack'),
  useSnackbar: () => {
    return {
      enqueueSnackbar: mockEnqueue
    };
  }
}));

I could't do this work :(.
Tried all options posted here. Any idea..?

I could't do this work :(.
Tried all options posted here. Any idea..?

same for me :(

i make it work like this : ( i know very nasty )

in test.js

    function NotistackServiceMock() {
        return {
            enqueueSnackbar: () => jest.fn(),
            closeSnackbar: () => jest.fn(),
        };
    }


    let notistackServiceMock;
    beforeEach(() => { 
        notistackServiceMock = NotistackServiceMock();
    });


    test('form input error', async () => {
        ...
        <MyComponent notistackService={notistackServiceMock}   />
        ... 
    });

in MyComponent.js

             ...
    import { useSnackbar } from 'notistack';

    export function MyComponent(props) {
        const { enqueueSnackbar } = props.notistackService || useSnackbar();
        return ( ... ) 
    }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

usama-asfar picture usama-asfar  ·  3Comments

khanhdinovative picture khanhdinovative  ·  3Comments

iamhosseindhv picture iamhosseindhv  ·  7Comments

alexisab picture alexisab  ·  5Comments

lsansaa picture lsansaa  ·  7Comments