在 React Native 中,如何使用浅渲染测试我的组件?
对于 React,我使用 浅渲染 用于对我的 React 组件进行单元测试的技术.我可以在 React Native 中做类似的事情吗?
For React, I use Shallow Rendering techniques for unit testing my React components. Can I do something similar in React Native?
我已经按照说明设置了 Jest,但可以找不到任何关于测试我的组件的文档.我想用 React Native 来做完整的 TDD,就像我用 React 一样.
I've followed the instructions to set up Jest, but can't find any documentation on testing my components. I would like to do full TDD with React Native in the same way I do with React.
我认为 enzyme 是您的选择'正在寻找.
I think enzyme is what you're looking for.
它为您提供了一个 shallow
函数,允许您进行浅比较(根据需要).
It provides you a shallow
function which allows you to make a shallow comparison (as you want).
Enzyme 可以与所有流行的测试运行程序(如 Mocha、Jest、Karma 等)一起使用.完整列表可以在在图书馆的 github 页面上找到.
Enzyme can be used along with all of the popular test runners (like Mocha, Jest, Karma etc). Full list can be found on the library's github page.
示例:
import {shallow} from 'enzyme';
describe('<MyComponent />', () => {
it('should render three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.length(3);
});
});
要进一步阅读,您可以查看酶的 Shallow渲染 API 或 docs 一般.
For the further reading you can take a look on enzyme's Shallow Rendering API or docs in general.