我是Jest的新手,我正在尝试模拟上下文HOC函数以测试我的组件 这是我的文件夹结构
基本上,我正在尝试模拟HomeScreen组件正在使用的homeContext.js文件。根据文档,我在contexts文件夹下创建了一个__mocks__
文件夹,并创建了一个homeContext.js
文件
以下是文件的内容:
/contexts/__mocks__/homeContext.js
const mock = jest.fn().mockImplementation(() => {
console.log('Mocking');
return {
withHomeContext: jest.fn(() => {}),
};
});
module.exports = mock;
contexts/homeContext.js
export const withHomeContext = ChildComponent => props => {
console.log('Not Hitting');
return (
<HomeContext.Consumer>
{context => <ChildComponent {...props} homeContext={context} />}
</HomeContext.Consumer>
);
};
这是我尝试在scenes/home/index.test.js
jest.mock('../../contexts/homeContext');
import React from 'react';
import {mount} from 'enzyme';
import HomeScreen from './index';
describe('<HomeScreen /> renders', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(<HomeScreen />);
expect(wrapper).toBeDefined();
});
})
这就是我正在测试的组件如何使用它
import * as React from 'react';
//Context
import {withHomeContext} from '../../contexts/homeContext';
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
relatedItems: [],
};
}
render() {
//Some render logic
}
}
export default withHomeContext(HomeScreen);
请帮助我为什么我的__mocks__/homeContext.js
从未被命中,而是命中了实际的文件,该文件记录了控制台日志(“未命中”)