Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

reactjs - Writing test cases using Jest and Enzyme

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...