тестирование стандартных значений параметров функции с помощью jest - PullRequest
0 голосов
/ 20 марта 2019

в приведенном ниже фрагменте кода, как я могу проверить регистр объекта по умолчанию в функции actualData.

когда я запускаю покрытие jest, я получаю ответвление не как 100%, потому что я не написал тестовый пример для объектарегистр по умолчанию.

как я могу проверить это

Пожалуйста, посмотрите приведенный ниже фрагмент кода.Любая помощь приветствуется:)

// sample.js

    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

 const Mapper = require('./Sample');


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

1 Ответ

1 голос
/ 20 марта 2019

Это даст вам покрытие кода для этой строки:

test('resolveData should handle error', () => {
  const model = new Mapper({ users: [] });
  expect(() => { model.resolveData(); }).toThrow();
})

... сказав это, вы, вероятно, должны просто удалить аргумент по умолчанию, поскольку resolveData всегда вызывается со всеми тремя аргументами.

Вы также можете удалить try/catch из обеих функций, поскольку catch ничего не делает, кроме как сгенерирует ошибку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...