[英]Differences between defining shallow in describe block and in every test block?
Lets say we have the following component tree: Mycomponent Component 1 Component 2 Component 3假设我们有以下组件树: Mycomponent Component 1 Component 2 Component 3
Mycomponent is the owner component and contains three child components. Mycomponent 是所有者组件,包含三个子组件。
The thing we want to check is if the each single component renders correctly.我们要检查的是每个组件是否正确渲染。
I can test this by using shallow rendering as following:我可以通过使用浅渲染来测试这一点,如下所示:
it('renders <Component1 /> component', () => {
const wrapper = shallow(<Mycomponent/>);
expect(wrapper.find(Component1). length).toHavelengthOf(1);
});
it('renders <Component2 /> component', () => {
const wrapper = shallow(<Mycomponent/>);
expect(wrapper.find(Component2). length).toHavelengthOf(1);
});
Instead of defining wrapper for each test, is it possible to define it in describe block scope so each test can reach that wrapper so i dont have to define it for each test?不是为每个测试定义包装器,是否可以在描述块范围内定义它,以便每个测试都可以到达该包装器,因此我不必为每个测试定义它?
You can use shallow
in beforeEach
block.您可以在
beforeEach
块中使用shallow
。 You'd better get a new wrapper for each test case.你最好为每个测试用例获得一个新的包装器。 So that the results of each test case will not be affected.
这样每个测试用例的结果都不会受到影响。 Maintain good isolation between test cases.
保持测试用例之间的良好隔离。
Eg例如
index.tsx
: index.tsx
:
import React, { Component } from 'react';
export const Component1 = () => <span>component 1</span>;
export const Component2 = () => <span>component 2</span>;
export const Component3 = () => <span>component 3</span>;
class MyComponent extends Component {
render() {
return (
<div>
<Component1></Component1>
<Component2></Component2>
<Component3></Component3>
</div>
);
}
}
export default MyComponent;
index.test.tsx
: index.test.tsx
:
import MyComponent from './';
import { Component1, Component2, Component3 } from './';
import React from 'react';
import { shallow } from 'enzyme';
describe('59980692', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<MyComponent></MyComponent>);
});
it('renders <Component1 /> component', () => {
expect(wrapper.find(Component1)).toHaveLength(1);
});
it('renders <Component2 /> component', () => {
expect(wrapper.find(Component2)).toHaveLength(1);
});
it('renders <Component3 /> component', () => {
expect(wrapper.find(Component3)).toHaveLength(1);
});
});
unit test results:单元测试结果:
PASS src/stackoverflow/59980692/index.test.tsx (15.157s)
59980692
✓ renders <Component1 /> component (57ms)
✓ renders <Component2 /> component (4ms)
✓ renders <Component3 /> component (6ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 17.468s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.