0
votes

I have a React component which is displaying count of data. In componentDidMount; getChannel (it is an axios get call api) function returns count and then this.setState update workedOnDataTotalElementCount value. I am trying to write a test for componentDidMount and the api call. How can I write a test for updating a workedOnDataTotalElementCount after api call ? I am using Jest(^21.2.1) and Enzyme(3.1.1).

class DocumentFromCounterCompany extends Component {
constructor(props) {
   super(props)

  this.state = {
     workedOnDataTotalElementCount: 0
  }
}

componentDidMount() {
  getChannel().then(res => {
    if (!res) return
    else {
      this.setState({ workedOnDataTotalElementCount: res.data.channel })
    }
  })
 }

I use axios in api calls. My api code is:

export function getChannel(params) {
  return GetAjaxAsync({
    url: `api/indexcenter/documents?${params}`,
    isDirectCall: true,
    onStart: () => {
      return {
        fetching: true
      }
    },
    onSuccess: data => {
      return {
        channel: data
      }
    },
    onError: err => {
      return {
        error: err
      }
    },
    onFinally: response => {
      return {
        fetching: false
      }
    }
  })
}

 
1
Where does getChannel come from? Show the code - slideshowp2
I added getChannel code :) - Bertug

1 Answers

0
votes

Use jest.mock() to mock getChannel function of api module. Since getChannel is asynchronous, we need to use a helper function like flushPromises to wait for the completion of the promise micro task.

E.g.

index.jsx:

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

export class DocumentFromCounterCompany extends Component {
  constructor(props) {
    super(props);

    this.state = {
      workedOnDataTotalElementCount: 0,
    };
  }

  componentDidMount() {
    getChannel().then((res) => {
      if (!res) return;
      else {
        this.setState({ workedOnDataTotalElementCount: res.data.channel });
      }
    });
  }

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

index.test.jsx:

import { shallow } from 'enzyme';
import { DocumentFromCounterCompany } from '.';
import { getChannel } from './api';

jest.mock('./api');

function flushPromises() {
  return new Promise((resolve) => setTimeout(resolve, 0));
}

describe('68267026', () => {
  it('should pass', async () => {
    getChannel.mockResolvedValueOnce({ data: { channel: 100 } });
    const wrapper = shallow(<DocumentFromCounterCompany />);
    await flushPromises();
    expect(wrapper.state('workedOnDataTotalElementCount')).toEqual(100);
  });
});

unit test result:

 PASS  examples/68267026/index.test.jsx (14.25 s)
  68267026
    ✓ should pass (9 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   83.33 |       50 |      80 |   90.91 |                   
 api.js    |      50 |      100 |       0 |      50 | 2                 
 index.jsx |      90 |       50 |     100 |     100 | 15                
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        17.09 s