子组件引用给出错误

时间:2018-06-04 09:06:55

标签: reactjs jestjs enzyme

这是我用来进行所有提取调用的方法。

static sendJsonRequest(address, action, requestType, jsonData, queryParams, successCallback, errorCallback,showLoader,httpErrorCallback, serverUrl){
    localStorage.setItem("_lastUpdatedTime", Date.now());

    ProjectStore.setLodingCount(ProjectStore.getLodingCount() + 1);
    if(showLoader){
      BusyLoader.showLoader();
    }
    var finalURL = Client.getServiceURL( address, action, queryParams, serverUrl);
    fetch(finalURL, {
      method: requestType,
      headers: {
        'content-type': 'application/json; charset=utf-8',
        'Authorization': 'Bearer ' + localStorage.getItem("access_token"),
        'pragma': 'no-cache',
        'cache-control': 'no-cache'
      },
      body: String(requestType).toLowerCase() === "get" ? undefined : JSON.stringify(jsonData)
    })
    .then(function(response) {
      if (!response.ok) {
          throw Error(response.statusText);
      }
      return response.json();
    })
    .then(function(jsonObj) {
      if(ProjectStore.getLodingCount() > 0){
        ProjectStore.setLodingCount(ProjectStore.getLodingCount() - 1);
      }
      if(ProjectStore.getLodingCount() === 0){
        BusyLoader.hideLoader();
      }
      successCallback(jsonObj);
    })
    .catch(function(err) {
      if(ProjectStore.getLodingCount() > 0){
        ProjectStore.setLodingCount(ProjectStore.getLodingCount() - 1);
      }
      if(ProjectStore.getLodingCount() === 0){
        BusyLoader.hideLoader();
      }
        errorCallback(err);
    });
  }

我正在尝试编写测试用例,每次编写测试用例时我都会收到错误:

BusyLoader.objBusyLoader.setState is not a function

这是BusyLoader组件

的实现
import React, {Component} from 'react';
import Loading from 'react-loading';
export default class BusyLoader extends Component {
        static objBusyLoader = {};
        constructor(props) {
            super(props);
            BusyLoader.objBusyLoader = this;
            this.state = {
                    busyIcon:false,
                    color:"#0876b7",
                    width:100,
                    height:100
            };
        }

        static showLoader(){
            BusyLoader.objBusyLoader.setState({
                busyIcon:true
            });
    }

    static hideLoader(){
        BusyLoader.objBusyLoader.setState({
            busyIcon:false
        });
    }

        render(){
        var absStyle = {
            position: "absolute",
            top: "50%",
            left: "50%",
            marginTop: "-50px",
            marginLeft: "-100px",
            zIndex : 2017
        }

        return(<div className="overlay" style={{display : this.state.busyIcon ? "" : "none"}}>
                <div  style={absStyle}>
                    <Loading type='spinningBubbles' color={this.state.color} width={this.state.width}  height={this.state.height}/>
                </div>
            </div>);
    }
}

这是我试图编写的测试用例

import React from 'react';
import {shallow} from 'enzyme';
import Client from '../Client.jsx';

describe('<Client />', () => {
  it('should fetch data from service', () => {
    const mockData = {  goodResponse: 'yes' };
    jest.spyOn(window, 'fetch').mockImplementation(() => Promise.resolve(mockData));
    Client.sendJsonRequest();
  });
});

任何人都可以在这里告诉我这个问题,并建议我如何写这个案例。

1 个答案:

答案 0 :(得分:0)

您正在调用试图呼叫showLoader的静态方法(objBusyLoader.setState)。但是objBusyLoader在构造函数中赋值。这是一种习惯,因为有一个访问“实例变量”的静态方法有点“扭曲”。

必须创建至少一个BusyLoader实例才能使其正常工作:

import React from 'react';
import {shallow} from 'enzyme';
import Client from '../Client.jsx';
import BusyLoader from '../BusyLoader.jsx';

describe('<Client />', () => {
  beforeAll(() => {
    // instantiate the BusyLoader class once, this will assign BusyLoader.objBusyLoader
    shallow(<BusyLoader />);
  })

  it('should fetch data from service', () => {
    const mockData = {  goodResponse: 'yes' };
    jest.spyOn(window, 'fetch').mockImplementation(() => 
      Promise.resolve(mockData));
    Client.sendJsonRequest();
  });
});

但是,你一定要复习你的设计,因为这有“难闻的味道”。