【问题标题】:How to mock a nested component import in react js and test using react testing library如何在反应 js 中模拟嵌套组件导入并使用反应测试库进行测试
【发布时间】:2021-05-02 03:45:09
【问题描述】:

我有一个名为SearchBox 的组件,它在SearchSection 中使用,而MyComponent 又使用它。 SearchBox 有一个使用setTimeout() 的方法。

SearchBox.tsx

import React from 'react';
export class SearchBox extends React.Component {
  
  private timer: (ReturnType<typeof setTimeout> | null) = null;

  public asyncmethod() {
    if (this.timer !== null) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      doSomething();
    }, 1000);
    console.log('using original class method');
  }

  render() {
    return (
      <div>
        ...
        ...
        {this.asyncmethod()}
        ...
        ...
      </div>
    );
  }
}

SearchSection.tsx

import React from 'react';
import { SearchBox } from './SearchBox';

export class SearchSection extends React.Component {
  render() {
    return <SearchBox />;
  }
}

MyComponent.tsx

import React from 'react';
import { SearchSection } from './SearchSection';

export class MyComponent extends React.component {
  render() {
    return <SearchSection />;
  }
}

现在我想使用react-testing-library 测试MyComponent,并且我想使用不使用setTimeout 的重写类方法来模拟SearchBox。我尝试了以下

testUtil.tsx

import { SearchBox } from './SearchBox';

class MockedSearchBox extends SearchBox {
  public asyncMethod() {
    doSomething();
    console.log('using mocked class method');
  }
}

MyComponent.test.tsx

import { MockedSearchBox } from './testUtil.tsx'
import { render } from '@testing-library/react';
import { MyComponent } from './MyComponent';
 
describe('My component', () => {
  jest.mock('./SearchBox', () => {
    return {
      SearchBox: MockedSearchBox
    }
  });

  test('that my component shows text', () => {
    const { getByText } = render(<MyComponent />);
    expext(getByText('Search mock text')).toBeDefined();
  });
});

但这不起作用。即使在编写了上述代码之后,也会调用原始类方法。我做错了什么?

【问题讨论】:

    标签: reactjs typescript unit-testing jestjs react-testing-library


    【解决方案1】:

    你在嘲笑./SearchBox 模块,所以你最好不要扩展原来的SearchBox 组件。您应该为SearchBox 组件创建一个简单的模拟版本。

    例如

    MyComponent.tsx:

    import React from 'react';
    import { SearchSection } from './SearchSection';
    
    export class MyComponent extends React.Component {
      render() {
        return <SearchSection />;
      }
    }
    

    SearchBox.tsx:

    import React from 'react';
    
    export class SearchBox extends React.Component {
      private timer: ReturnType<typeof setTimeout> | null = null;
    
      public asyncmethod() {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          console.log('doSomething');
        }, 1000);
        console.log('using original class method');
        return 'search real text';
      }
    
      render() {
        return <div>{this.asyncmethod()}</div>;
      }
    }
    

    SearchBoxSection.tsx:

    import React from 'react';
    import { SearchBox } from './SearchBox';
    
    export class SearchSection extends React.Component {
      render() {
        return <SearchBox />;
      }
    }
    

    testUtil.tsx

    import React from 'react';
    
    export class MockedSearchBox extends React.Component {
      public asyncMethod() {
        console.log('using mocked class method');
        return 'Search mock text';
      }
      render() {
        return <div>{this.asyncMethod()}</div>;
      }
    }
    

    MyComponent.spec.tsx:

    import React from 'react';
    import { render } from '@testing-library/react';
    import { MyComponent } from './MyComponent';
    
    jest.mock('./SearchBox', () => {
      const { MockedSearchBox } = require('./testUtil');
    
      return {
        SearchBox: MockedSearchBox,
      };
    });
    
    describe('My component', () => {
      test('that my component shows text', () => {
        const { getByText } = render(<MyComponent />);
        expect(getByText('Search mock text')).toBeDefined();
      });
    });
    

    单元测试结果:

     PASS  examples/65933863/MyComponent.spec.tsx (9.544 s)
      My component
        √ that my component shows text (59 ms)
    
      console.log
        using mocked class method
    
          at MockedSearchBox.asyncMethod (examples/65933863/testUtil.tsx:5:13)
    
    -------------------|---------|----------|---------|---------|-------------------
    File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -------------------|---------|----------|---------|---------|-------------------
    All files          |     100 |      100 |     100 |     100 | 
     MyComponent.tsx   |     100 |      100 |     100 |     100 | 
     SearchSection.tsx |     100 |      100 |     100 |     100 | 
     testUtil.tsx      |     100 |      100 |     100 |     100 | 
    -------------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        11.973 s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2022-07-13
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      相关资源
      最近更新 更多