is not a function 问题解决

来源:5-4 添加Button 测试代码 第一部分

_麦当

2021-03-09

之前跑测试的时候遇到了xxx is not a function 的问题,我引入@testing-library/jest-dom/extend-expect这个包以后就好了

yarn run v1.22.10
$ jest
 FAIL  src/components/Button/button.test.tsx
  test button component
    ✕ should render the correct default component (32 ms)

  ● test button component › should render the correct default component

    TypeError: expect(...).toBeInTheDocument is not a function

       9 |     const element = wrapper.getByText('Nice');
      10 |     expect(element).toBeTruthy();
    > 11 |     expect(element).toBeInTheDocument();
         |                     ^
      12 |     expect(element?.tagName).toEqual('BUTTON');
      13 |     expect(element).toHaveClass('btn btn-default');
      14 |   })

      at Object.<anonymous> (src/components/Button/button.test.tsx:11:21)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        3.423 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Process finished with exit code 1

解决如下:

import React from 'react';
import {render} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'; // 引入这个
import Button from './index';

describe('test button component', () => {
  it('should render the correct default component', () => {
    const wrapper = render(<Button>Nice</Button>);
    const element = wrapper.getByText('Nice');
    expect(element).toBeTruthy();
    expect(element).toBeInTheDocument();
    expect(element?.tagName).toEqual('BUTTON');
    expect(element).toHaveClass('btn btn-default');
  })
})


写回答

1回答

张轩

2021-03-09

同学你好 请问这个是你自己找到了解决方案嘛? 恭喜你~

0
1
_麦当
非常感谢!
2021-03-09
共1条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2128 学习 · 959 问题

查看课程