gpt4 book ai didi

javascript - 以 Angular Testing 函数

转载 作者:行者123 更新时间:2023-11-27 22:48:59 25 4
gpt4 key购买 nike

我正在尝试编写一个测试来验证加载页面时是否调用了函数。我试图监视它,但它说它不存在。

有人可以给我一些关于如何正确监视它的帮助吗?

这是 Angular 代码:

(function () {
angular
.module('uotc')
.controller('reportGroupArchiveCtrl', ReportGroupArchiveCtrl);

ReportGroupArchiveCtrl.$inject = ['$scope', '$http', '$stateParams', '$q'];

function ReportGroupArchiveCtrl($scope, $http, $stateParams, $q) {
$scope.reportType = $stateParams.reportType;
$scope.templateTypeId = $stateParams.templateTypeId;
$scope.group = $stateParams.group;

//Initialize the page
activate();

function activate() {
//Call the API to get the generated reports for this group
$http.get('api/url/params....)
.then(getGeneratedReportsComplete)
.catch(apiCallFailed);
}

function getGeneratedReportsComplete(data, status, headers, config) {
//do stuff
};
function apiCallFailed(e) {
return null;
}
}
})();

这是测试:

describe('Controller', function () {
var stateparams, controller, scope;

beforeEach(angular.mock.module('uotc'));

beforeEach(angular.mock.inject(function (_$controller_, _$rootScope_) {
stateparams = { reportType: 'Vendor', templateTypeId: 2, group: 'VENDOR_1' };
scope = _$rootScope_.$new();
controller = _$controller_('reportGroupArchiveCtrl',{
$scope: scope,
$stateParams:stateparams
});
spyOn(controller, 'getGeneratedReportsComplete')

}));

describe('is loaded', ()=> {
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');

$httpBackend
.when('GET', 'api/url/params)
.respond(200, '123')
$httpBackend.flush();

}));
it('calls the generated reports API', ()=> {
expect(controller.getGeneratedReportsComplete()).toHaveBeenCalled();
})
})

});

最佳答案

这是错误的:

    expect(controller.getGeneratedReportsComplete()).toHaveBeenCalled();

这样更好:

    expect(controller.getGeneratedReportsComplete).toHaveBeenCalled();

您将函数本身传递给expect;你不应该调用它。

另一个问题是 getGenerateReportsComplete 在构造函数内声明为局部变量,因此在构造函数之外无法访问它,并且您无法监视它。相反,在 this 对象上定义它:

this.getGeneratedReportsComplete = (data, status, headers, config) => {
//do stuff
};

当然,您也需要将其称为 this.getGenerateReportsComplete

关于javascript - 以 Angular Testing 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204617/

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