使用Jest和Enzyme编写测试用例 [英] Writing test cases using Jest and Enzyme

查看:174
本文介绍了使用Jest和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);
      }
    );
  }

运行测试时,在函数中,行app.outageCenterService.getContact(reqObject)引发错误,提示TypeError: Cannot read property 'getContact' of undefined.我理解它是因为outageCenterService是全局定义的,并且玩笑/酶无法找到它.但是我不知道如何解决这个问题.

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?

推荐答案

您可以考虑使用globals配置

You could consider use the globals config

http://facebook.github.io/jest/docs /api.html#globals-object 或创建文件并

并在全局范围内为您创建一个模拟玩笑,然后您就可以从测试中访问它了.

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.

这篇关于使用Jest和Enzyme编写测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆