带有redux的mocha:预期undefined等于true

时间:2017-01-25 14:54:22

标签: reactjs redux mocha react-intl

我正在尝试使用redux和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);
  });
});

但我得到了这个结果:

  <Navbar />
    1) calls componentDidMount


  0 passing (73ms)
  1 failing

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

有人可以给我一个建议,我该如何解决?

1 个答案:

答案 0 :(得分:1)

错误是因为,componentDidMount未在测试中进行间谍活动。您可以使用sinon来解决此问题。例如,

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);
  });
});

旁注: - 如果你想在测试中使用react-intl,我建议使用所述的辅助函数here