Jest测试在渲染时不会因错误而失败

时间:2019-06-19 21:55:27

标签: javascript reactjs unit-testing jestjs

我试图修复一些可以通过的单元测试,而不管渲染中发生了什么。

import React from 'react';
import Component from './Component';

describe('Basic component tests', () => {
  it('renders nothing on initial load', () => {
    const component = shallow(<Component/>);

    expect(component.exists()).toBe(false);
  });
});

问题是,当我运行此测试时,console.error出现错误,但是无论如何该测试均通过。我该如何检查渲染是否正确无误地发生?如果确实发生错误,则测试失败?

输出示例:

Debugger listening on ws://127.0.0.1:44345/7a8a35fb-7e19-4d92-8dc0-ea274fa1646c
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
  console.error src/components/universal/Component.js:91
    TypeError: Cannot read property 'includes' of undefined
        at includes (/home/frozendragon/code/application/src/components/universal/Component.js:412:45)
        at Array.filter (<anonymous>)
        at Component.filter [as getPackagesByIds] (/home/frozendragon/code/application/src/components/universal/Component.js:412:29)
        at Component.getPackagesByIds (/home/frozendragon/code/application/src/components/universal/Component.js:86:36)
        at tryCatch (/home/frozendragon/code/application/node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:45:40)
        at Generator.invoke [as _invoke] (/home/frozendragon/code/application/node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:271:22)
        at Generator.prototype.(anonymous function) [as next] (/home/frozendragon/code/application/node_modules/@babel/polyfill/node_modules/regenerator-runtime/runtime.js:97:21)
        at asyncGeneratorStep (/home/frozendragon/code/application/src/components/universal/Component.js:4176:103)
        at _next (/home/frozendragon/code/application/src/components/universal/Component.js:4178:194)

------------------|----------|----------|----------|----------|-------------------|
File              |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------------|----------|----------|----------|----------|-------------------|
All files         |    33.57 |       15 |    35.48 |    34.38 |                   |
 Component.js     |    33.57 |       15 |    35.48 |    34.38 |... 65,566,569,574 |
------------------|----------|----------|----------|----------|-------------------|

1 个答案:

答案 0 :(得分:0)

最简单的测试是仅验证您可以查询DOM中的特定元素,例如

expect(component.exists('.some-class')).to.equal(true);
相关问题