简体   繁体   English

如何使用 Jest 和 Enzyme 测试 componentDidMount() 中的方法?

[英]How to test a method in componentDidMount() with Jest and Enzyme?

I want to cover the code below with unit test:我想用单元测试覆盖下面的代码:

export class DataTrack extends Component<DataTrackProps> {
componentDidMount() {
    this.setData();
    
    if (this.props.enableDataTrack) {
        this.pushData();
    }
}

private setData() {
    window.globalData = {
        app_platform        : "I"
    }
}

private getData() {
        this.dataTrack= {
            command: "EVENT",
            name: "data",
            data: {
                app_embed_name : "it"
            }
        };

        return this.dataTrack;
}

private pushData() {
    window.analyticsData = window.analyticsData || [];
    window.analyticsData .push(this.getData());
}
}

and started with covering the componentDidMount with the test below:并开始使用以下测试覆盖componentDidMount

it("should run the methods in the componentDidMount", () => {
    const props: DataTrackProps= {
        enableDataTrack: true,
    };

    const setDataOnMount = jest.spyOn(DataTrack.prototype, 'setData'); // spy
    const wrapper = shallow(<DataTrack{...props}  />); // create
    expect(setDataOnMount ).toHaveBeenCalledTimes(1); // test
});

But I'm getting the error: Argument of type '"setData"' is not assignable to parameter of type 'FunctionPropertyNames<Required<DataTrack>>'.但我收到错误: Argument of type '"setData"' is not assignable to parameter of type 'FunctionPropertyNames<Required<DataTrack>>'.

I also don't know how to test the methods setData , getData and pushData with Jest/Enzyme.我也不知道如何使用 Jest/Enzyme 测试方法setDatagetDatapushData

Can someone help me with this?有人可以帮我弄这个吗? How can I cover the methods inside the componentDidMount and the methods self?如何涵盖componentDidMount内部的方法和方法自身?

You can test if the window.globalData and window.analyticsData are set with the correct value.您可以测试window.globalDatawindow.analyticsData是否设置了正确的值。 There is no need to install spy to the private methods.无需将 spy 安装到私有方法。

Besides, you should restore window.globalData and window.analyticsData property to the initial state.此外,您应该将window.globalDatawindow.analyticsData属性恢复为初始 state。 Avoid test cases influencing each other.避免测试用例相互影响。

Eg例如

DataTrack.tsx : DataTrack.tsx

import React, { Component } from 'react';

declare global {
  interface Window {
    globalData: any;
    analyticsData: any;
  }
}

interface DataTrackProps {
  enableDataTrack?: boolean;
}
export class DataTrack extends Component<DataTrackProps> {
  dataTrack = {};
  componentDidMount() {
    this.setData();
    if (this.props.enableDataTrack) {
      this.pushData();
    }
  }

  private setData() {
    window.globalData = { app_platform: 'I' };
  }

  private getData() {
    this.dataTrack = {
      command: 'EVENT',
      name: 'data',
      data: {
        app_embed_name: 'it',
      },
    };
    return this.dataTrack;
  }

  private pushData() {
    window.analyticsData = window.analyticsData || [];
    window.analyticsData.push(this.getData());
  }
  render() {
    return <div>data track</div>;
  }
}

DataTract.test.tsx : DataTract.test.tsx

import { shallow } from 'enzyme';
import React from 'react';
import { DataTrack } from './DataTract';

describe('DataTract', () => {
  afterEach(() => {
    window.globalData = undefined;
    window.analyticsData = undefined;
  });
  test('should push and set data', () => {
    shallow(<DataTrack enableDataTrack />);
    expect(window.globalData).toEqual({ app_platform: 'I' });
    expect(window.analyticsData).toEqual([
      {
        command: 'EVENT',
        name: 'data',
        data: {
          app_embed_name: 'it',
        },
      },
    ]);
  });

  test('should set data', () => {
    shallow(<DataTrack enableDataTrack={false} />);
    expect(window.globalData).toEqual({ app_platform: 'I' });
    expect(window.analyticsData).toBeUndefined();
  });
});

test result:测试结果:

 PASS  examples/70364599/DataTract.test.tsx (8.509 s)
  DataTract
    ✓ should push and set data (5 ms)
    ✓ should set data

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 componentDidMount中的jest酶测试方法 - jest enzyme test method in componentDidMount 在componentDidMount中开玩笑的酶测试方法失败,但控制台显示它正在工作 - jest enzyme test method in componentDidMount fails but console shows that it is working ComponentDidMount() 中 Axios 请求的 Jest/酶单元测试 - Jest/Enzyme Unit Test on Axios Requests in ComponentDidMount() 笑话和酵素| 在componentDidMount中测试PropTypes函数 - Jest & Enzyme | Test PropTypes Function in componentDidMount 使用Jest / Enzyme测试componentDidMount中的多个提取 - Test multiple fetches in componentDidMount with Jest/Enzyme 使用 jest/enzyme 在 React 上测试 ComponentDidMount 失败 - Test Failing in ComponentDidMount on React using jest/enzyme 当 Component.prototype 返回 undefined 时,如何使用 jest/enzyme 对 componentDidMount 进行单元测试? - How to unit test componentDidMount using jest/enzyme when Component.prototype returns undefined? 如何使用 JEST 和 ENZYME 测试在 componentDidMount 中调用 Axios 的 React 组件? - How to Test a Reactcomponent which has Axios call in componentDidMount using JEST with ENZYME? 如何为 componentDidMount() 编写单元测试用例并导出默认 connect(null, updateProps)(<componentname> ) 在 React 中使用 JEST/酶?</componentname> - How to write unit test case for componentDidMount() and export default connect(null, updateProps)(<ComponentName>) with JEST/Enzyme in React? 在 Enzyme 中如何在 componentDidMount 方法中等待 API 调用? - In Enzyme how to wait for an API call in the componentDidMount method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM