component.js
<React.Fragment>
{ state.data ? jsx : null }
</React.Fragment>
export default withStyles(styles, { withTheme: true })(Component);
我无法深入研究用withStyles(material-ui样式)包装的组件,因此包装器未定义返回。 我已经尝试过dive()方法。
我的测试代码如下。
Component.test.js
configure ({adapter : new EnzymeAdapter()});
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const setup = (initialState={},props={}) => {
const store = mockStore(initialState);
const wrapper = shallow(<Component store={store} {...props}/>).dive();
return wrapper;
};
const findAttrByTest = (wrapper,val) => {
return wrapper.find(`[data-test="${val}"]`);
};
describe("renders <Component>", () => {
let wrapper;
beforeEach(() => {
const props = { };
const initialState = {
value: '',
id : ''
}
wrapper = setup(initialState,props);
});
test("it should return `some text` when no data is loaded", () => {
const component = findAttrByTest(wrapper,"data-loading");
expect(component.length).toBe(1);
});
});
答案 0 :(得分:1)
通过使用.WrappedComponent,您可以访问内部组件并删除dive()
。
测试代码将是这样
configure ({adapter : new EnzymeAdapter()});
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const setup = (initialState={},props={}) => {
const store = mockStore(initialState);
const wrapper = shallow(<Component.WrappedComponent store={store} {...props}/>);
return wrapper;
};
const findAttrByTest = (wrapper,val) => {
return wrapper.find(`[data-test="${val}"]`);
};
describe("renders <Component>", () => {
let wrapper;
beforeEach(() => {
const props = { };
const initialState = {
value: '',
id : ''
}
wrapper = setup(initialState,props);
});
test("it should return `some text` when no data is loaded", () => {
const component = findAttrByTest(wrapper,"data-loading");
expect(component.length).toBe(1);
});
});