首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Moxios不起作用的Jest酶测试用例模拟API

Moxios不起作用的Jest酶测试用例模拟API
EN

Stack Overflow用户
提问于 2021-01-13 20:48:14
回答 1查看 284关注 0票数 0

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

代码语言:javascript
复制
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,但它没有模拟请求。

代码语言:javascript
复制
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()
    })
  })
})
EN

回答 1

Stack Overflow用户

发布于 2021-01-14 18:35:23

  1. 您无需手动调用componentDidMount()getAllData()方法。

与酶v3一样,shallow应用编程接口不会调用componentDidMountcomponentDidUpdate等React生命周期方法

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

  1. respondWith方法的返回值是一个承诺,你应该确保它被解决/拒绝。因此,您需要在承诺被解决或拒绝后进行断言。

例如。

MyComponent.tsx

代码语言:javascript
复制
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

代码语言:javascript
复制
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();
      });
    });
  });
});

单元测试结果:

代码语言:javascript
复制
 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65702308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档