单元测试ES6承诺(.then,.catch)

时间:2017-10-24 17:52:18

标签: javascript angularjs unit-testing ecmascript-6 es6-promise

我正在使用AngularJS和ES6,所以我想为ES6编写一个单元测试(不使用angular.mock ......)这就是我试图测试它的方法。但问题是it('resolves its promise with the current data'它失败并带有

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

我根据this删除了done(),但测试总是通过,无关toEqual什么!也许响应变量设置不正确。

有人有任何想法吗??

data.service.js

    export class DataService {
     'ngInject';
      constructor($log, $http) {
        this.$log = $log;
        this.$http = $http;
      }
      getData(url, name) {
        return this.$http.get(url)
          .then((response) => {
            return {data: response.data, version: response.version)};
          })
          .catch((error) => {
            this.$log.error('Failed for getData.\n' + angular.toJson(error.data, true));
            throw error.data || {};
          });
       }
    }

data.service-spec.js

import {DataService} from './data.service';

let sysUnderTest, mapSelectionServiceMock, http;

describe('http.get', () => {
  let temperaturePromise;
  let promiseHelper;
  let getDataPromise;

  beforeEach(() => {
    let fetchPromise = new Promise((resolve, reject) => {
      promiseHelper = {
        resolve: resolve,
        reject: reject
      };
    });

    // http mock
    http = {
      get: () => {}
    };
    spyOn(http, 'get').and.returnValue(fetchPromise);
    sysUnderTest = new DataService(null, http, null, null, null);
    getDataPromise = sysUnderTest.getData('sampleURL');
  });

  it('getData', () => {
    expect(http.get).toHaveBeenCalled();
    expect(getDataPromise).toEqual(jasmine.any(Promise));
  });

  describe('on successful get', function() {
    beforeEach(function() {
      let response = new Response(JSON.stringify({
        data: 78,
        version: 1
      }));
      promiseHelper.resolve(response);
    });

    it('resolves its promise with the current data', function(done) {
        getDataPromise.then(function(data) {
          expect(data).toEqual(79987);
          done();
        });
    });
  });
});

0 个答案:

没有答案