how to test and resolve Controller data (.then function()) promise and get orginal Data in Jasmine2

前端 未结 2 1039
小鲜肉
小鲜肉 2020-12-07 06:14
    I am testing a controller that uses a service that returns a promise. I need to resolve promise. I am using Jasmine 2. 

    Here is Spec code

      beforeEach(         


        
2条回答
  •  遥遥无期
    2020-12-07 06:41

    First of all you are "spying on" the wrong method. We use spyOn for two reasons:

    • To expect(method).toHaveBeenCalled
    • To mock the return value

    In your case the spyOn does not achieve any of these two.

    You should spyOn the $http instead. Since the actual http call is not required for your test, the reason being: the objective is not to test $http.

    this.$http = $http;
    spyOn(this, '$http').and.callFake(function(args) {
        return {
            then: function(fn) {
                return fn('response');
            }
        };
    });
    

    And in it block:

    it('getDateRangeData return Data obj', function() {
        myService.getDateRangeData('test')
        .then(function(response) {
            console.log('Success', response);
            expect(response).toEqual('response');
        });
        expect(this.$http).toHaveBeenCalledOnceWith('test');   
    });
    

提交回复
热议问题