使用jest在React组件内部模拟外部类方法

时间:2018-01-26 12:19:28

标签: reactjs mocking jestjs

我正在尝试测试组件方法,它在内部执行对外部资源的网络调用。阅读文档后,我仍然无法弄清楚如何做到这一点。有人可以帮忙吗?这是我的代码(为简洁起见隐藏了一些部分):

我的组件:

import React from 'react'
import ResourceService from '../../modules/resource-service'

export default class SliderComponent extends React.Component {
  setActiveSlide = (activeSlide) => {
    ResourceService.getData({
      id: activeSlide,
    }).then((data) => {
      if (data) {
        this.setState({
          data,
        })
      }
    })
  }
}

资源服务:

import axios from 'axios'

export default class ResourceService {
  static getData(params) {
    return axios.post('/api/get_my_data', params)
      .then((resp) => resp.data)
  }
}

期望的测试(据我所知):

import React from 'react'
import { mount, configure } from 'enzyme'
import SliderComponent from '../../../app/components/slider'

test('SliderComponent changes active slide when setActiveSlide is  
called', () => {
  const wrapper = mount(
    <SliderComponent />
  );
  wrapper.instance().setActiveSlide(1);
  // some state checks here
});

我需要在ResourceService.getData内进行模拟SliderComponent调用,我真的无法理解这样做...

2 个答案:

答案 0 :(得分:0)

尝试使用axios-mock-adapter模拟测试中的postreq。

看起来应该是这样的(可能还需要一些调整):

import React from 'react'
import { mount, configure } from 'enzyme'
import SliderComponent from '../../../app/components/slider'
import axios from'axios';
import MockAdapter = from'axios-mock-adapter';

test('SliderComponent changes active slide when setActiveSlide is  
called', () => {
let mock = new MockAdapter(axios)
//you can define the response you like
//but your params need to be accordingly to when the post req gets called
 mock.onPost('/api/get_my_data', params).reply(200, response) 

  const wrapper = mount(
    <SliderComponent />
  );
  wrapper.instance().setActiveSlide(1);
  // some state checks here
});

请务必查看axios-mock-adapter的文档

答案 1 :(得分:0)

您可以在测试中导入ResourceService并使用getData模拟方法jest.fn(() => ...)。这是一个例子:

import React from 'react'
import { mount, configure } from 'enzyme'
import ResourceService from '../../../modules/resource-service'
import SliderComponent from '../../../app/components/slider'

test('SliderComponent changes active slide when setActiveSlide is  
called', () => {
   // you can set up the return value, you can also resolve/reject the promise 
   // to test different scnarios
   ResourceService.getData = jest.fn(() => (
      new Promise((resolve, reject) => { resolve({ data: "testData" }); }));

  const wrapper = mount(<SliderComponent />);

  wrapper.instance().setActiveSlide(1);

  // you can for example check if you service has been called
  expect(ResourceService.getData).toHaveBeenCalled();
  // some state checks here
});