【问题标题】:Jest Enzyme Test Case mock API with Moxios not workingMoxios 的 Jest Enzyme 测试用例模拟 API 不工作
【发布时间】:2021-04-18 11:42:59
【问题描述】:

这是我使用 getAllData 方法调用 API 并将数据设置为状态的组件代码:

class MyComponent extends Component {
 state = {
   allStatus: []
 }
 componentDidMount() {
  this.getAllData();
 }
 getAllData = async() => {
   let res = await apiCalls(`${Config.masterUrl}/ContentState`, 'GET', {}, `/user-data`, false);
   if (res) {
     this.setState({allStatus: res});
   }
  }
}

这是测试用例,首先我调用 componentDidMount 并调用 getAllData 方法,然后使用 moxios 模拟 API,但它不会模拟请求。

describe('Render MyComponent Component', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = setup(initialState);
    moxios.install();
  });
  afterEach(() => {
    moxios.uninstall();
  })
  
  it("should call getAllData API Success",  async(done) => {
    const responseData = {
      status: 200,
      error: null,
      data: [Array] // for example
    }
    await wrapper.instance().componentDidMount();
    await wrapper.instance().getAllData()
    moxios.wait(function() {
      const request = moxios.requests.mostRecent();
      request.respondWith(responseData)
      expect(wrapper.instance().state.allStatus.length).not.toBe(0)
      done()
    })
  })
})

【问题讨论】:

  • 如果您还没有配置 moxios 来响应它发出的请求,如何才能完成对 getAllData 的调用?此外,您不应该直接调用组件方法,对componentDidMount 的调用已经调用了getAllData,并且一旦组件被挂载,React 就会调用componentDidMount
  • @jonrsharpe 你能添加一个测试吗?

标签: reactjs jestjs mocking enzyme moxios


【解决方案1】:
  1. 您无需手动调用componentDidMount()getAllData() 方法。

从 Enzyme v3 开始,shallow API 确实调用了 React 生命周期方法,例如 componentDidMountcomponentDidUpdate

  1. 你应该先安装moxios,然后浅渲染组件。因为当我们浅渲染(调用componentDidMountgetAllData)组件时,模拟应该准备好了。

  2. respondWith 方法的返回值是一个承诺,你应该确保它被解析/拒绝。所以你需要在promise被resolved或者reject之后再做断言。

例如

MyComponent.tsx:

import axios from 'axios';
import React, { Component } from 'react';

async function apiCalls(url, method) {
  return axios({ url, method }).then((res) => res.data);
}

export class MyComponent extends Component {
  state = {
    allStatus: [],
  };
  componentDidMount() {
    this.getAllData();
  }
  getAllData = async () => {
    let res = await apiCalls(`http://localhost:3000/api/ContentState`, 'GET');
    if (res) {
      this.setState({ allStatus: res });
    }
  };
  render() {
    return <div>MyComponent</div>;
  }
}

MyComponent.test.tsx:

import React from 'react';
import { shallow } from 'enzyme';
import moxios from 'moxios';
import { MyComponent } from './MyComponent';

describe('Render MyComponent Component', () => {
  let wrapper;
  beforeEach(() => {
    moxios.install();
    wrapper = shallow(<MyComponent></MyComponent>);
  });
  afterEach(() => {
    moxios.uninstall();
  });

  it('should call getAllData API Success', (done) => {
    const responseData = {
      status: 200,
      response: [1, 2, 3],
    };
    moxios.wait(function () {
      const request = moxios.requests.mostRecent();
      request.respondWith(responseData).then(() => {
        expect(wrapper.state('allStatus')).toHaveLength(3);
        done();
      });
    });
  });
});

单元测试结果:

 PASS  examples/65702308/MyComponent.test.tsx (5.34 s)
  Render MyComponent Component
    ✓ should call getAllData API Success (246 ms)

-----------------|---------|----------|---------|---------|-------------------
File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------------|---------|----------|---------|---------|-------------------
All files        |     100 |       50 |     100 |     100 |                   
 MyComponent.tsx |     100 |       50 |     100 |     100 | 17                
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        6.505 s

【讨论】:

  • 如果在 componentDidMount 中调用多个 API 怎么办,那么我如何知道哪个 API 正在使用您的测试用例进行测试。示例我的组件现在有 2 个 API 调用:componentDidMount() { this.getAllData(); this.getUserList()}
猜你喜欢
  • 2019-08-30
  • 2019-06-11
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 2019-07-24
  • 2019-08-28
  • 1970-01-01
  • 2019-01-29
相关资源
最近更新 更多