【问题标题】:How to test Reac Lazy inside an object如何在对象内部测试 React Lazy
【发布时间】:2021-04-17 18:08:22
【问题描述】:

在我正在进行的项目中,有一些命名导出,如下面的对象:

export const object = {
    component: React.lazy(() => import('some-component'))
}

(它们有更多属性,但为了简洁起见,我只展示这个)

问题

当我尝试使用 Jest 对其进行测试时,我无法在 React.lazy 中进行测试:

我尝试模拟 React.lazy 没有成功:

jest.mock('react', () => ({
  lazy: () => {
    return 'lazy'
  },
}))

describe('Auth route object', () => {
  it('', () => {
    expect(auth).toBeDefined()
    expect(auth[0].component).toBe('lazy')
  })
})

这会返回passed,但它一直抱怨覆盖范围。

我如何模拟/测试它?

ps:我需要这个文件至少 90% 的覆盖率,这就是为什么我不能忽略它。

【问题讨论】:

  • 模拟组件,而不是 React 本身。
  • 我知道如何模拟命名导出的唯一方法是:导入默认值并模拟它,返回自身(如果需要)并将其命名为导出。我不知道如何嘲笑只是懒惰。
  • 等等,我想我弄错了,@EstusFlask(喜欢这个名字顺便说一句)。你是在告诉我要模拟“某些组件”吗?
  • 是的,没错。模拟它并渲染一个使用它的组件。

标签: javascript reactjs testing jestjs


【解决方案1】:

您可以使用@testing-library/react 来测试React.lazy() 方法。另外,如果懒加载组件过于复杂,只想测试包含该组件的父组件,可以使用jest.mock()方法来提供子组件的mocked版本。

例如

index.tsx:

import React, { Suspense } from 'react';

export const object = {
  component: React.lazy(() => import('./OtherComponent')),
};

export function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <object.component />
      </Suspense>
    </div>
  );
}

OtherComponent.tsx:

import React from 'react';

export default function OtherComponent() {
  return <div>other component</div>;
}

index.test.tsx:

import { MyComponent } from './';
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

function MockedOtherComponent() {
  return <div>mocked other component</div>;
}

jest.mock('./OtherComponent', () => {
  return MockedOtherComponent;
});

describe('67141439', () => {
  it('should pass', async () => {
    render(<MyComponent />);
    const textToMatch = await screen.findByText(/mocked other component/);
    expect(textToMatch).toBeInTheDocument();
  });
});

测试结果:

 PASS  examples/67141439/index.test.tsx (10.487 s)
  67141439
    ✓ should pass (40 ms)

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

软件包版本:

"react": "^16.14.0"
"jest": "^26.6.3"
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.2.2",

【讨论】:

  • 我已经在用这个方法了。问题是我的公司使用 codeclimate,他们计算 very 单一测试。所以,这个组件是 100%,但文件本身是仍然 50% 的覆盖率,我需要覆盖它。
猜你喜欢
  • 1970-01-01
  • 2019-07-07
  • 2023-02-04
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-24
相关资源
最近更新 更多