如何测试和解析Controller数据(.then function())并在Jasmine2中获取原始数据

时间:2018-12-05 09:34:24

标签: angularjs unit-testing testing karma-jasmine jasmine2.0

n

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

任何人都可以很快帮忙。

2 个答案:

答案 0 :(得分:0)

如果您希望spyOn实际上使用正确的实现而不是模拟,则可以使用callThrough()而不是callFake()

像这样尝试:

spyOn(myService, "getDateRangeData").and.callThrough();

答案 1 :(得分:0)

首先,您正在“监视”错误的方法。 我们使用spyOn有两个原因:

  • expect(method).toHaveBeenCalled
  • 模拟return value

在您的情况下,spyOn不能达到这两个条件中的任何一个。

您应该改为spyOn $http。由于测试不需要实际的http调用,原因是:目标不是测试$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');   
});