我正在Jest中为React组件编写单元测试但是在这两种情况下我都得到错误的响应。
foo.js
function fooRender(){
if(data === true)
{
return <div class="hello" id="helloId">Hello</div>;
}
else{
return <div className="hi" id="hiId">Hi</div>}
}
foo.spec.js
describe('check foo Component',()=>{
describe('without data',()=>{
const mount = shallow(<Foo data={false}/>
it('data is false',()=>{
expect(mountedComponent.contains('hello')).toBeNull();
})
});
describe('without data',()=>{
const mount = shallow(<Foo data={true}/>
it('data is true',()=>{
expect(mountedComponent.contains('hello')).toBeNull();
});
});
});
在两个测试案例中,我都是假的。在一个案例中一定是真的而在另一个案件中则是假的。在控制台中获取错误
is only meant to be run on a single node. 0 found instead.
如果未定义任何元素。
如何为这两种方案编写测试用例?
答案 0 :(得分:0)
这是单元测试解决方案:
foo.tsx
:
import React from 'react';
function Foo({ data }) {
if (data === true) {
return (
<div className="hello" id="helloId">
Hello
</div>
);
} else {
return (
<div className="hi" id="hiId">
Hi
</div>
);
}
}
export { Foo };
foo.test.tsx
:
import { Foo } from './foo';
import React from 'react';
import { shallow } from 'enzyme';
describe('check foo Component', () => {
it('data is false', () => {
const wrapper = shallow(<Foo data={false} />);
expect(wrapper.contains('Hi')).toBeTruthy();
});
it('data is true', () => {
const wrapper = shallow(<Foo data={true} />);
expect(wrapper.contains('Hello')).toBeTruthy();
});
});
具有覆盖率报告的单元测试结果:
PASS src/stackoverflow/50540892/foo.test.tsx
check foo Component
✓ data is false (10ms)
✓ data is true (1ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
foo.tsx | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 4.253s, estimated 9s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/50540892