如何在 Jasmine2 中测试和解析控制器数据(.then function())承诺并获取原始数据 [英] how to test and resolve Controller data (.then function()) promise and get orginal Data in Jasmine2

查看:17
本文介绍了如何在 Jasmine2 中测试和解析控制器数据(.then function())承诺并获取原始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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(inject(function ($controller, $rootScope, _myService_, _$q_, _$rootScope_, _$httpBackend_, $http) {


         scope = $rootScope.$new();
         $q = _$q_;
         $httpBackend = _$httpBackend_;
         $rootScope = _$rootScope_;
         myService = _myService_;
$http = $http;
         ctrl =  $controller('Ctrl', { '$scope': scope, 'myService': myService });
     spyOn(myService, "getDateRangeData").and.callThrough();

      }));


        it('getDateRangeData return Data obj', function() {

    myService.getDateRangeData().then(function(response) {
      console.log('Success', response);
    }); 
        scope.$digest()      

      });

service js
function getDateRangeData(obj) {
  return $http({
    method: 'POST',
    url: 'https:URL',
     headers: {
       'Content-Type': 'application/json',
       'X-Auth-Token': self.token
     },
    data: obj
  })
}

控制台未返回任何 obj.Shows 错误.意外请求:POST https:URL没有更多的要求.我需要来自 Ctrl 的数据.在 Crtl 中,我正在获取数据但不在测试用例中.推迟.如何获取 Api 数据.Api 数据是对象.或者还有另一个方法可以让 Ctrl 返回承诺解决并获取数据?在请求发送的地方添加了服务 js 代码.

console not returning any obj.Shows error.Unexpected request: POST https:URL No more request expected. i need data from Ctrl . In Crtl I am getting data but not in testcase. deferred. how to get Api data. Api data is object. or there is another aprroch to get Ctrl return promise to resolve and getData? added sevice js code where request send.

谁能尽快帮忙.

推荐答案

首先,您监视"了错误的方法.我们使用 spyOn 有两个原因:

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

  • To expect(method).toHaveBeenCalled
  • 模拟返回值

在您的情况下,spyOn 没有实现这两者中的任何一个.

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

你应该 spyOn 代替 $http.由于您的测试不需要实际的 http 调用,原因是:目标不是测试 $http.

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

it 块中:

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

这篇关于如何在 Jasmine2 中测试和解析控制器数据(.then function())承诺并获取原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆