0

I'm trying to wrote test for my react component which using redux and react-intl:

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Navbar from 'Navbar';
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux';
import messages from '../src/l10n/en.json'
import { IntlProvider } from 'react-intl'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
const store = mockStore({})


describe('<Navbar />', () => {

  it('calls componentDidMount', () => {
    const wrapper = mount(
      <Provider store={store}>
        <IntlProvider locale={ "en" } messages={ messages }>
          <Navbar />
        </IntlProvider>
      </Provider>
    );
    expect(Navbar.prototype.componentDidMount.calledOnce).to.equal(true);
  });
});

But I got this result:

  <Navbar />
    1) calls componentDidMount


  0 passing (73ms)
  1 failing

  1) <Navbar /> calls componentDidMount:
     AssertionError: expected undefined to equal true

Can some one give me an advise how can I fix it?

Pavel
  • 2,103
  • 4
  • 23
  • 41

1 Answers1

1

The error is because, componentDidMount is not spy'ed in the test. You could use sinon to do fix this issue. For instance,

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import Navbar from 'Navbar';
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux';
import messages from '../src/l10n/en.json'
import { IntlProvider } from 'react-intl'
import { spy } from 'sinon';

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
const store = mockStore({})


describe('<Navbar />', () => {
  it('calls componentDidMount', () => {
    spy(Navbar.prototype, 'componentDidMount');
    const wrapper = mount(
      <Provider store={store}>
        <IntlProvider locale={ "en" } messages={ messages }>
          <Navbar />
        </IntlProvider>
      </Provider>
    );
    expect(Navbar.prototype.componentDidMount.calledOnce).to.equal(true);
  });
});

On a side note:- If you want to use react-intl in tests, I would suggest to use helper functions as described here

anoop
  • 3,229
  • 23
  • 35
  • I tried to use helper with react component without redux: https://gist.github.com/pustovalov/95b4222c77d2dad9255cab83bc99351d But I got this an error: ` 1) have text: TypeError: Cannot read property 'context' of undefined ` – Pavel Jan 27 '17 at 01:46
  • it's working without helpers https://gist.github.com/pustovalov/2d4932a898156b973c38efd86025cd4b – Pavel Jan 27 '17 at 02:47
  • Hmm that was a suggestion for a best practice. That error most probably because of react-intl issues. Would you be able to accept this answer? – anoop Jan 27 '17 at 05:57