【问题标题】:How to write React-jest testing如何编写 React-jest 测试
【发布时间】:2022-01-23 10:06:38
【问题描述】:

以下是我的 index.js 文件。在那里我想测试应用程序是否在没有崩溃的情况下呈现。

import ReactDOM from 'react-dom';
import { StrictMode } from 'react';

import App from './App';
import './index.scss';

ReactDOM.render(
   <StrictMode>
     <App />
   </StrictMode>,
  document.getElementById('root')
);

我编写的 index.test.js 文件如下所示。即使通过了测试,它也有一条未覆盖的线。

/* eslint-env jest */
import ReactDOM from 'react-dom';
import { StrictMode } from 'react';

jest.mock('react-dom', () => ({ render: jest.fn() }));

describe('index.js', () => {
   it('renders without crashing', () => {
     ReactDOM.render(StrictMode);
     expect(ReactDOM.render).toHaveBeenCalledWith(StrictMode);
   });
});

第 1 行标记为未覆盖。

    import ReactDOM from 'react-dom'; 

那么你能帮我改进一下这条线的测试用例吗?

【问题讨论】:

  • 这不会测试它是否在没有崩溃的情况下呈现;什么都没有被渲染。这将测试是否使用 StrictMode 组件调用了渲染,而不是其他任何东西。

标签: reactjs unit-testing jestjs react-dom


【解决方案1】:

最好测试渲染的输出,而不是模拟和测试实现细节。因为index.js里面的代码会在你import/require这个模块时立即执行。在导入模块之前,我们需要一个设置测试环境。欲了解更多信息,请参阅testing-recipes

index.jsx:

import ReactDOM from 'react-dom';
import React from 'react';
import { StrictMode } from 'react';

import App from './App';

ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  document.getElementById('root')
);

App.jsx:

import React from 'react';

export default function App() {
  return <div>app</div>;
}

index.test.jsx:

import { unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';

describe('70444704', () => {
  let container = null;
  beforeEach(() => {
    container = document.createElement('div');
    container.id = 'root';
    document.body.appendChild(container);
  });

  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });
  test('should pass', () => {
    act(() => {
      require('./');
    });
    expect(container.textContent).toBe('app');
  });
});

测试结果:

 PASS  examples/70444704/index.test.jsx (12.701 s)
  70444704
    ✓ should pass (599 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 App.jsx   |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.396 s

软件包版本:

"react": "^16.14.0",
"react-dom": "^16.14.0",
"jest": "^26.6.3",

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2022-11-17
    • 2017-04-06
    • 1970-01-01
    • 2018-09-17
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多