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

前端 未结 2 1036
小鲜肉
小鲜肉 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

    If you want the spyOn to actually use the correct implementation instead of the mock you can use callThrough() instead of callFake().

    Try it like this:

    spyOn(myService, "getDateRangeData").and.callThrough();
    
    0 讨论(0)
  • 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');   
    });
    
    0 讨论(0)
提交回复
热议问题