我有一个 HOC 组件,它包装了 React 的上下文 API,如下所示
import React from 'react';
import { AppContext } from './Context';
export function withAppContext(Component) {
return function WrapperComponent(props) {
return (
<AppContext.Consumer>
{state => <Component {...props} context={state} />}
</AppContext.Consumer>
);
};
}
和另一个使用这个 HOC 的组件
class Hello extends Component {
render() {
return (
<Fragment>
<p>{this.props.context.state.name}</p>
<p>{this.props.context.state.age}</p>
<p>{this.props.user}</p>
</Fragment>
)
}
}
export default withAppContext(Hello);
我打算编写一个单元测试来测试Hello
组件。为了实现这一点,我有以下单元测试
const getAppContext = (context = {
state : {
"name" : "Jane Doe",
"age" : 28
}
}) => {
// Will then mock the AppContext module being used in our Hello component
jest.doMock('../../../context/Context', () => {
return {
AppContext: {
Consumer: (props) => props.children(context)
}
}
});
// We will need to re-require after calling jest.doMock.
// return the updated Hello module that now includes the mocked context
return require('./Hello').Hello;
};
describe('Hello', () => {
test('Verify state from Context API', ()=> {
const Hello = getAppContext();
const wrapper = mount(<Hello />);
})
})
但它在这一行失败
const wrapper = mount(<Hello />);
并显示以下消息
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your componentfrom the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `WrapperComponent`.
46 | test('Verify state from Context API', ()=> {
47 | const Hello = getAppContext();
> 48 | const wrapper = mount(<Hello />); | ^
49 | expect(wrapper.find('li').hostNodes().length).toBe(2);
50 | expect(wrapper.html()).toBe("<ul><li>Name : Jane Doe</li><li>Age : 28</li></ul>")
51 | })
你能告诉我我在这里做错了什么吗?
谢谢