首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用jest测试函数参数的默认用例

使用jest测试函数参数的默认用例
EN

Stack Overflow用户
提问于 2019-03-20 14:50:24
回答 1查看 1.3K关注 0票数 0

在下面的代码片段中,我如何检查actualData函数中的对象默认大小写。

当我运行jest复盖时,我得到的分支不是100%,因为我没有为对象默认用例编写测试用例。

我怎样才能检查那个?

请看下面的代码片段。感谢您提供的任何帮助:)

// sample.js

代码语言:javascript
复制
    let data = {
  users: [
    {
      terms: ["service|/users"],
      conditions: ["view", 'create']
    },
    {
      terms: ["service|/users-details"],
      conditions: ["view"]
    },
    {
      terms: ["service|/usersNew"],
      conditions: ["view"]
    },
    {
      terms: ["list|searchuser"],
      conditions: ["view"]
    },
    {
      terms: ["list|createuser"],
      conditions: ["view", "create"]
    },
    {
      terms: ["service|/user-contacts"],
      conditions: ["view"]
    },
    {
      terms: ["service|/user-location"],
      conditions: ["view"]
    },
    {
      terms: ["page|supplierlist|button|select"],
      conditions: ["enable"]
    },
    {
      terms:["page|supplierlist|button|create-new"],
      conditions: ["disable"]
    }
  ]
};


class Mapper{
  constructor(data){
    this.currentIndex = -1;
    this.data = this.extractData(data);
  }

  resolveData(terms, object={}, conditions){
    try{
      return terms.reduce((result, string) => {
        const [key, value] = string.split(/\|(.+)/);
        if (value && value.includes('|')) {
          result[key] = result[key] || {};
          this.resolveData([value], result[key], conditions);
        } else {
          result[key] = result[key] || [];
          this.currentIndex = this.currentIndex + 1;
          result[key].push({ [value]: conditions[this.currentIndex] });
        }
        return result;
      }, object);
    }catch(error){
      throw error
    }
  }


  extractData(data){
    try{
      let terms = data.users.map(o => o.terms)
      terms = [].concat(...terms);
      const conditions = data.users.map(o => o.conditions);
      return this.resolveData(terms, {}, conditions)
    }catch(error){
      throw error
    }
  }
}

// sample.test.js

代码语言:javascript
复制
 const Mapper = require('./Sample');


describe('Sample File test cases', () => {
    test('should throw an error', () => {
        const resolvedSample = {}
        expect(() => {
          const model = new Mapper(resolvedSample)
        }).toThrow(TypeError);
    })
})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-20 19:36:50

这将为您提供该行的代码覆盖率:

代码语言:javascript
复制
test('resolveData should handle error', () => {
  const model = new Mapper({ users: [] });
  expect(() => { model.resolveData(); }).toThrow();
})

...having说,你可能应该删除默认参数,因为resolveData总是用所有三个参数调用的。

您也可以从这两个函数中删除try/catch,因为catch除了抛出错误之外不做任何事情。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55255003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档