我是React Hooks的新手,我想实现的目标是测试一个React组件(称为CardFooter),该组件包含对useEffect钩子的调用,该钩子被触发以触发全局上下文变量。
CardFooter.js:
const CardFooter = props => {
const [localState, setLocalState] = useState({
attachmentError: false
});
const globalContext = useContext(GlobalContext);
React.useEffect(()=> {
setLocalState({
...localState,
attachmentError: globalContext.data.attachmentError
});
},[globalContext.data.attachmentError]);
}
CardFooter.test.js:
import Enzyme, { shallow } from 'enzyme';
Enzyme.configure({ adapter: new Adapter() });
describe('<CardFooter />', () => {
let useEffect;
const mockUseEffect = () => {
useEffect.mockImplementation(f => f());
};
useEffect = jest.spyOn(React, "useEffect");
mockUseEffect(); //
it('should render correctly with no props.', () => {
}
const mockUseEffect = () => {
useEffect.mockImplementation(f => f());
};
useEffect = jest.spyOn(React, "useEffect");
mockUseEffect();
const wrapper = shallow(<CardFooter />);
expect(toJson(wrapper)).toMatchSnapshot();
});
运行测试时出现的错误是:
TypeError: Cannot read property 'attachmentError' of undefined
我尝试了此处介绍的方法:https://medium.com/@pylnata/testing-react-functional-component-using-hooks-useeffect-usedispatch-and-useselector-in-shallow-9cfbc74f62fb。但是,似乎shallow不会选择模拟的useEffect实现。我还尝试模拟useContext和globalContext.data.attachmentError。似乎什么都没有。
答案 0 :(得分:0)
试试这个。注意“jest.spyOn”放在“beforeEach”中
beforeEach(() => {
jest.spyOn(React, "useEffect").mockImplementationOnce(cb => cb()());
// .... other things ....
}