问题描述
我正在尝试在我的 React 应用程序中进行快照测试。我已经在使用 react-testing-library 进行一般的单元测试。然而,对于快照测试,我在网上看到了不同的方法,使用 react-test-renderer 或 react-testing 库。这里有3个例子,它们之间有什么区别,什么是首选?
1.使用反应测试渲染器
test('renders correctly',() => {
const tree = renderer
.create(<Link page="http://www.facebook.com">Facebook</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
});
2.使用 react-testing-library 和 asFragment()
test('renders correctly',() => {
const { asFragment } = render(<NotFound />);
expect(asFragment()).toMatchSnapshot();
});
3.使用 react-testing-library 和容器
test('renders the component',() => {
const container = render(<Component />)
expect(container.firstChild).toMatchSnapshot()
})
解决方法
经过大量实验后,我选择了选项 2(使用 asFragment() 的 react-testing-library),因为它可以生成更清晰的快照。选项 1 (react-test-renderer) 生成的输出包含组件属性和其他不相关的详细信息。