0

我正在尝试为使用 redux 和 react-intl 的 react 组件编写测试:

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

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

4

1 回答 1

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在测试中使用,我建议使用此处描述的辅助函数

于 2017-01-26T00:22:28.790 回答