在ES6中为默认函数参数创建单元测试

时间:2018-02-05 22:16:17

标签: javascript unit-testing ecmascript-6 frontend code-coverage

以下代码能够解析来自服务器的特定响应。为了确保在未定义serviceResponse参数时响应将是一个空数组,如输出,我使用ES6功能提供的默认值。

我想知道您是否知道更好的方法来覆盖或测试locationHistoryParser函数上定义的默认函数值。

来源

function _getLagLngCoordinates(coordinates) {
 ...
}

function _getCoordinates(coordinates) {
  return coordinates.locations ?
    _getLagLngCoordinates(coordinates.locations) :
    _getLagLngCoordinates(coordinates);
}


function locationHistoryParser(serviceResponse = '[]') {
  return _getCoordinates(JSON.parse(serviceResponse));
}

测试套件

describe('locationHistoryParser', () => {

  describe('retrieving a valid response', function () {

    describe('managing an array of objects', function () {
      it('should return an array of coordinates parsed properly', () => {
        ...
      });
    });

    describe('managing an object with locations key', function () {
      it('should return an array of coordinates parsed properly', () => {
        ...
      });
    });
  });

  describe('retrieving an invalid response', function () {

    it('should return an empty array', () => {
      const inputData = undefined;
      const expectedObject = [];

      const response = locationHistoryParser(inputData);

      expect(response).toEqual(expectedObject);
    });
  });

});

0 个答案:

没有答案