Writing test cases using Jest and Enzyme

独自空忆成欢 提交于 2019-12-11 15:54:11

问题


I am working on writing test cases for a project. I am writing the test for my Container. The container has a function which is as shown below:

getContactDetails = (reqObject) => {
    app.outageCenterService.getContact(reqObject).then(
      response => {
        app.logger.getLogger().info('Below is the response...');
        app.logger.getLogger().info(this.state.contactDetails);
        this.setState({contactDetails: response.contactDetails},()=>{});
        if (this.state.contactDetails.isContactPresent) {
          this.setState({ isVisible: true });
        } else {
          this.setState({ isVisible: false });
        }
      },
      reject => {
        app.logger.getLogger().info(reject);
      }
    );
  }

While running the test,in the function,the line app.outageCenterService.getContact(reqObject) throws an error saying TypeError: Cannot read property 'getContact' of undefined. I understand its because outageCenterService is globally defined and jest/enzyme is not able to find it. But I don't know how to solve this issue.

My test looks something like this:

  describe('test the OutageAlert Component', () => {
    let outageAlert, errorHandlerFn;
    errorHandlerFn=jest.fn();
    getContactFn=jest.fn();
    outageAlert = shallow(<OutageAlertComponent errorHandler={errorHandlerFn} getContact={getContactFn} />);
  });

Can anyone please help me with this on how to write the test case for this scenario?


回答1:


You could consider use the globals config

http://facebook.github.io/jest/docs/api.html#globals-object or create a file and

and create a mock in jest for you global, then you can access it from your test.

Alternatively you could have your container accepting an argument for your contact

getContactDetails = (reqObject, contact) => { ...}

so you can pass it in your test and wherever you container is being used.



来源:https://stackoverflow.com/questions/53390624/writing-test-cases-using-jest-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!