gpt4 book ai didi

javascript - 在 AngularJS Controller 中对 Promise 调用进行单元测试时遇到问题

转载 作者:行者123 更新时间:2023-12-02 16:36:47 25 4
gpt4 key购买 nike

SupportedLanguagesServices get 方法返回一个 promise,该 promise 在 Controller 中解析如下:

    angular.module('App').controller('MyController', ['SupportedLanguagesService',
function(SupportedLanguagesService) {

var self = this;
self.supportedLanguages = [];

SupportedLanguagesService.get().success(
function(response) {
self.supportedLanguages = response;
});

}]);

这是我编写的测试,但它不起作用:

    describe('Controller: MyController', function() {

beforeEach(module('App'));

var rootScope, controller;

beforeEach(inject(function($controller, $rootScope, SupportedLanguagesService, $q) {

var deferred = $q.defer();
deferred.resolve([{name:"English", code:"en"},{name:"Portugues", code:"pt_BR"]);
spyOn(SupportedLanguagesService, 'get').andReturn(deferred.promise);

rootScope = $rootScope;
controller = $controller;
}));

it('should get SupportedLanguages', function() {
rootScope.$digest();
var ctrl = controller('MyController');
expect(ctrl.supportedLanguages.length).toEqual(2);
});

});

它在语句上抛出异常:var ctrl =controller('MyController');

感谢您的帮助。

最佳答案

您可以更改为 then,而不是 success(这是一个 $http 回调),它在所有 Promise 上都可用。这将允许您轻松模拟 promise (而不用担心 $httpBackend:

    SupportedLanguagesService.get().then(
function(response) {
self.supportedLanguages = response.data;
});

然后,您需要使用 Controller 的构造函数,然后然后调用$digest。因此,切换到此应该可以帮助您实现目标:

it('should get SupportedLanguages', function() {

var ctrl = controller('MyController');
rootScope.$digest();
expect(ctrl.supportedLanguages.length).toEqual(2);
});

您还可以使用$q.when简化设置代码:

var response = [{name:"English", code:"en"},{name:"Portugues", code:"pt_BR"}];
spyOn(SupportedLanguagesService, 'get').andReturn($q.when(response));

关于javascript - 在 AngularJS Controller 中对 Promise 调用进行单元测试时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27863806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com