当它包含在Provider组件中时,如何用mocha +酶+ chai测试反应原生组件

时间:2017-01-14 11:58:01

标签: testing react-native mocha mockery enzyme

我使用 mocha,酶,chai 和一些模拟库来进行测试。因此, TestComponent.js 的内容如下,我配置商店并将其传递给提供商,而 DeskScreen 是连接组件:

import mockery from "mockery";
import 'babel-polyfill';
import reactNativeSvgMock from "react-native-svg-mock";
mockery.enable();
mockery.registerMock("react-native-svg", reactNativeSvgMock);
var DeskScreen = require( '../app/containers/DeskScreen/DeskScreen');
import React, {View, Text, StyleSheet} from 'react-native';
import {Provider} from 'react-redux';
import {shallow, render, mount} from 'enzyme';
import {expect} from 'chai';
import configureStore from 'redux-mock-store';
import reducer from "../app/reducers";
import Button from "../app/containers/Common/Button";
import ButtonWithNoFlex from "../app/containers/Common/ButtonWithNoFlex";
const mockStore = configureStore([]);

describe('<Test />', () => {
    it('it should render 1 view component', () => {
        const store = mockStore(reducer);
        var comp = shallow(
         <Provider store={store}>
            <DeskScreen/>
        </Provider>
    );
        expect(button).to.have.length(1);
        expect(comp.find(View)).to.have.length(1);
    });
});

运行命令npm test后,它会生成以下内容:

1) it should render 1 view component


  0 passing (1s)
  1 failing

  1) <Test /> it should render 1 view component:
     AssertionError: expected { Object (root, unrendered, ...) } to have a length of 1 but got 0
      at Context.<anonymous> (test/TestComponent.js:22:41)

也许原因是我使用浅而不是mount,但据我所知mount不适用于react-native。无论如何,我想以某种方式测试连接组件。

1 个答案:

答案 0 :(得分:2)

我认为有两种方法可以解决问题。

1。导出普通组件

在组件文件中,将组件导出为可在测试中使用的命名导出。

// Export the plain component as named component
export class MyComponent {
    // ...
}

export default connect(mapStateToProps)(MyComponent);

您的测试通过命名导入导入普通合作伙伴:

import { MyComponent } from './MyComponent';

// Use it in your tests

2。通过shallow

提供上下文

如果您通过上下文提供商店,则可以使用连接的组件。这就是<Provider>的作用。

import { shallow } from 'enzyme';
import { createStore } from 'redux';

// reducer could be a real reducer or a mock fake reducer.
const store = createStore(reducer);

it('my test', () => {
    const wrapper = shallow(
        <MyComponent>,
        { context: { store } }
    );

    // test your component here
});