【发布时间】:2020-06-14 07:19:56
【问题描述】:
今天下午,Out 团队在使用 Jest 为我们的 <Avatar /> 组件编写 React 测试库 (RTL) 测试时遇到了一个场景。具体来说,我们想测试当加载失败(onError 被触发)时,<img /> 标记已从 DOM 中删除,以匹配预期的组件最终视图。出于某种原因,在<img /> DOM 元素上使用fireEvent 对我们来说并不是很明显,我们没有在网上找到这个明确的解决方案,所以我们想要分享。可以想象,这也适用于其他事件,例如 onLoad。 More about RTL Events.
it('should render with only initials when avatar image is NOT found', async() => {
const { container } = render(<Avatar {...defaultMocks} />);
const avatarImg = container.querySelector('img');
expect(avatarImg).toBeInTheDocument();
fireEvent(avatarImg, new Event('error'));
expect(avatarImg).not.toBeInTheDocument();
});
【问题讨论】:
标签: javascript jestjs react-testing-library