reactjs - 上下文 API 单元测试因 TypeError 而失败
问题描述
我有一个 HOC 组件WithContext
(在一个方便命名的文件中withContext.js
)如下
import React from 'react';
import { DEFAULT_STATE } from './store';
const MyContext = React.createContext(DEFAULT_STATE);
export function WithContext(Component) {
return function WrapperComponent(props) {
return (
<MyContext.Consumer>
{state => <Component {...props} context={state} />}
</MyContext.Consumer>
);
};
};
以及使用它的组件如下
import React from "react";
import { WithContext } from './withContext';
const MyComp = (context) => {
return (
<div className="flex dir-col" id="MyComp">
<p>This is a test</p>
</div>
)
};
export default WithContext(MyComp);
我还有一个旨在测试这个MyComp
组件的单元测试。单元测试如下
import React from "react";
import {shallow} from "enzyme";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { WithContext } from './withContext';
// We need to configure our DOM
import jsdom from 'jsdom'
const {JSDOM} = jsdom;
const {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window;
global.document = document;
global.window = document.defaultView
Enzyme.configure({
adapter : new Adapter()
})
beforeEach(() => {
jest.resetModules()
})
//Takes the context data we want to test, or uses defaults
const getMyContext = (context = {
state : {}
}) => {
// Will then mock the MyContext module being used in our MyComp component
jest.doMock('withContext', () => {
return {
MyContext: {
Consumer: (props) => props.children(context)
}
}
});
// We will need to re-require after calling jest.doMock.
// return the updated MyComp module that now includes the mocked context
return require('./MyComp').default;
};
describe("MyComp component loading check", () => {
test("Renders the MyComp component correctly", () => {
const MyCompContext = getMyContext();
const wrapper = shallow(<MyComp/>);
// make sure that we are able to find the header component
expect(wrapper.find(".flex").hostNodes().length).toBe(1);
});
});
但是,此测试一直失败并显示消息
TypeError: (0 , _withContext.WithContext) is not a function
};
export default WithContext(MyComp);
你能告诉我这里有什么问题吗?
谢谢
解决方案
看起来您正在模拟withContext
,jest.doMock
但您从工厂函数返回的模拟不包含WithContext
函数。
然后,当您在模块require('./MyComp').default
中使用withContext
模拟时,由于模拟未定义函数MyComp
而尝试失败时。export default WithContext(MyComp);
withContext
WithContext