我正在使用摩卡,酶,柴和一些模拟库来使测试成为可能。因此,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)
也许原因是我使用浅层而不是挂载,但据我所知,挂载不适用于反应原生。无论如何,我想以某种方式测试连接的组件。
我认为有两种2. 通过
方法可以使用解决问题。
1. 导出普通组件
在组件文件中,将组件导出为名为 export 的组件,您可以在测试中使用。
// 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
});