[英]Jest with React - How do you render an entire component and test it?
假设我有一个简单的App组件,并且正在对其进行测试,以查看它是否简单地返回了一个在屏幕上打印Hello World的div。 为了在测试文件中呈现App,功能助手是什么? 此外,为了测试正在呈现的HTML,在期望调用中调用的函数是什么?
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
describe("App", () => {
it('prints "HELLO WORLD" to the screen', () => {
expect(**App??**).**toRENDER??**("HELLO WORLD")
}
}
谢谢
使用airbnb的酶库是一个好习惯。
有一个将两者一起使用的示例
您的代码如下所示:
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import {shallow} from 'enzyme'
describe("App", () => {
it('prints "HELLO WORLD" to the screen', () => {
const wrapper = shallow(<App />)
expect(wrapper.text()).toBe("HELLO WORLD")
}
}
您可能想要查看Jest的快照测试 。 这就像调用一样简单:
import renderer from 'react-test-renderer';
describe('snapshot testing', () => {
it('should render App', () => {
const component = renderer.create(<App />);
const tree = component.toJSON();
expect(component).toMatchSnapshot();
});
});
快照文件将存储在__tests__/__snapshots__
文件夹中。 确保将这些快照文件提交到Git存储库中,以便其他贡献者可以对其组件进行快照。
有关如何使用React设置Jest快照测试的更多信息,请参阅此处,因为您将需要安装一些npm依赖项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.