【发布时间】:2020-04-20 12:29:29
【问题描述】:
我一直在尝试使用shallow 渲染组件,该组件由enzyme 提供。
组件正在使用来自react-router-dom 的useHistory。
const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);
describe('MyComponent', () => {
const baseProps = {
history: createMemoryHistory(),
location: createLocation(baseMatch.url),
match: baseMatch
};
beforeEach(() => {
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
});
afterEach(() => { jest.clearAllMocks() });
it('renders blah blah', () => {
const wrapper = shallow(<MyComponent {...baseProps} />);
// testing MyComponent here...
});
我提到了this post,并以同样的方式输入了jest.mock。
但是,这会导致TypeError: Cannot read property 'history' of undefined。
控制台说:
MyComponent › renders blah blah
TypeError: Cannot read property 'history' of undefined
24 | const MyComponent = (props: IProps) => {
25 | console.log('useHistory', useHistory);
> 26 | let history = useHistory();
奇怪的是,上面第 25 行中的 console.log 打印了 useHistory 的实现(换句话说,它不是未定义的)。
显然,useHistory 没有被嘲笑。
我怀疑useHistory 不能被shallow 嘲笑(在上面的帖子中,发帖人使用的是mount())。
但是,我不能 100% 确定,因为我无法从 enzyme 和 react-router 的文档中找到 shallow 是否与 useHistory 兼容。
shallow 可以与useHistory 一起使用吗?任何建议将不胜感激。
【问题讨论】:
标签: reactjs react-router react-hooks enzyme