unit test ES6 promises (.then, .catch)

萝らか妹 提交于 2019-12-12 19:20:30

问题


I'm using AngularJS and ES6, So I want to write a unit test for the ES6 (not using angular.mock ...) this is how I tried to test it. but the problem is it('resolves its promise with the current data' it fails with the

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

I removed the done() based on this but the test always passes, doesn't matter toEqual what!. maybe the response variable doesn't set correctly.

Does someone have any idea!?

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();
        });
    });
  });
});

来源:https://stackoverflow.com/questions/46917005/unit-test-es6-promises-then-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!