在React Jest-Test中从onClick模拟http.get方法

时间:2019-04-22 04:26:42

标签: reactjs jestjs enzyme

在开玩笑的测试中,我有以下模拟场景。 我必须调用OnClick方法的其他组件方法,请在此处输入代码

我试图模拟onclick正常工作。并进行通话也很好,但不能模拟.then返回值

文件:DashboardChart.js

import getIntentsSince from '../services/getIntentsSince';

initializeCharts() {
  // I want to mock this. I am not able to get .then response value

  getIntentsSince(this.state.nowDateTime, DateUtil.getPreviousDayTS(this.state.nowDateTime))
  .then((topIntents) => {
    // I have to cover the code. Which is here
  })
}


getChart(){
  this.setState({it has some code})
  this.initializeCharts()
}

render(){
  return (
    <button onClick={this.getChart}> get chart</button>
  )
}

文件:getIntentsSince.js

import HttpClient from 'custom-http-client';
const client = new HttpClient();

const getIntentsSince = (currentTime, fromIntervalTime) => {
    return client.get(`url`).then((data) => {
        return data;
    })

};

export default getIntentsSince;

这就是我尝试过的方式

import React from 'react';
import { shallow, mount } from 'enzyme';
import Dashboard from '../../src/components/DashboardChart';
import getIntentsSince from '../../src/services/getIntentsSince'
import mockHttpClient from 'axp-http-client';

const client = new mockHttpClient();
import mockData from './Intents.json'

describe('Dashboard Page test cases', () => {
    let mockValue = jest.mock('../../src/services/getIntentsSince', () => new Promise(resolve => resolve({getIntentsSince: () => {return mockData}})))
   beforeAll(()=> {
    dashboardMock = mount(<DashboardChart  getIntentsSince={mockValue}/>);
  });

1 个答案:

答案 0 :(得分:0)

这是基于您提供的代码的解决方案。

文件夹结构:

.
├── DashboardChart.spec.tsx
├── DashboardChart.tsx
├── custom-http-client.ts
└── getIntentsSince.ts

DashboardChart.tsx

import React, { Component } from 'react';
import getIntentsSince from './getIntentsSince';

const DateUtil = {
  getPreviousDayTS(datetime) {
    return datetime;
  }
};

interface IDashboardChartState {
  nowDateTime: string;
}

class DashboardChart extends Component<{}, IDashboardChartState> {
  constructor(props) {
    super(props);
    this.state = {
      nowDateTime: '2019'
    };
    this.getChart = this.getChart.bind(this);
  }

  public initializeCharts() {
    return getIntentsSince(this.state.nowDateTime, DateUtil.getPreviousDayTS(this.state.nowDateTime)).then(
      topIntents => {
        // I have to cover the code. Which is here
        console.log(topIntents);
      }
    );
  }

  public getChart() {
    this.setState({});
    this.initializeCharts();
  }
  public render() {
    return <button onClick={this.getChart}> get chart</button>;
  }
}

export default DashboardChart;

getIntentsSince.ts

import HttpClient from './custom-http-client';

const client = new HttpClient();

const getIntentsSince = (currentTime, fromIntervalTime) => {
  return client.get(`url`).then(data => {
    return data;
  });
};

export default getIntentsSince;

custom-http-client.ts

export default class HttpClient {
  public async get(url) {
    return 'real data';
  }
}

DashboardChart.spec.tsx

import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import DashboardChart from './DashboardChart';
import getIntentsSince from './getIntentsSince';

jest.mock('./getIntentsSince.ts', () => jest.fn());

describe('Dashboard Page test cases', () => {
  let wrapper: ReactWrapper;
  beforeAll(() => {
    wrapper = mount(<DashboardChart />);
  });

  afterEach(() => {
    jest.resetAllMocks();
    jest.restoreAllMocks();
  });

  it('should get indents since correctly', async () => {
    const mockedResponse = 'mocked response';
    (getIntentsSince as jest.MockedFunction<typeof getIntentsSince>).mockResolvedValueOnce(mockedResponse);
    const logSpy = jest.spyOn(console, 'log');
    const actualValue = await (wrapper.instance() as any).initializeCharts();
    expect(actualValue).toBeUndefined();
    expect(logSpy).toBeCalledWith(mockedResponse);
    expect(getIntentsSince).toBeCalledWith('2019', '2019');
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/55789099/DashboardChart.spec.tsx (6.208s)
  Dashboard Page test cases
    ✓ should get indents since correctly (14ms)

  console.log node_modules/jest-mock/build/index.js:860
    mocked response

--------------------|----------|----------|----------|----------|-------------------|
File                |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------------|----------|----------|----------|----------|-------------------|
All files           |    89.47 |      100 |    85.71 |    88.89 |                   |
 DashboardChart.tsx |    89.47 |      100 |    85.71 |    88.89 |             33,34 |
--------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.731s, estimated 9s

HTML覆盖率报告:

enter image description here

以下是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55789099