gpt4 book ai didi

angularjs - 如何根据 john papa 风格指南在 angularjs 中编写测试

转载 作者:行者123 更新时间:2023-11-28 20:14:19 25 4
gpt4 key购买 nike

我是 angularjs 中编写测试的新手。我有一个根据 john papa 风格指南编写的 Controller 。我需要在我的测试用例中访问 Controller 中的那些方法。我该怎么做?我正在使用 Jasmine 。我的示例代码是:

(function(){
angular.module('myapp')
.controller('AlertsController', AlertsController);
AlertsController.$inject = ['$scope', 'StorageFactory']
function AlertsController($scope, StorageFactory) {
var vm=this;
vm.createAlert=createAlert();
function createAlert(){
//function code
}
})

我的测试如下:

 'use strict';
describe('Controller: AlertsController', function() {
var AlertsController, scope, StorageFactory;

beforeEach(module('myapp'));
beforeEach(inject(function(_$controller_, _StorageFactory_, _$rootScope_) {
scope = _$rootScope_.$new();
AlertsController = _$controller_;
StorageFactory = _StorageFactory_;
}));

var createController = function() {
AlertsController('AlertsController', {
'$scope': scope,
'StorageFactory': StorageFactory
});

};
it('should create an alert', function() {
spyOn(StorageFactory, 'isLoggedIn').and.callFake(function() {
return true;
});
createController();
expect(AlertsController).toBeDefined();
AlertsController.createAlert();
});
});

出现以下错误:

TypeError: undefined is not a constructor (evaluating 'AlertsController.createAlert()') in /Users/Ramya/Documents/panitr_mobile/test/spec/controllers/AlertsCtrlSpec.js (line 57)
at /Users/Ramya/Documents/panitr_mobile/test/spec/controllers/AlertsCtrlSpec.js:57:37
PhantomJS 2.0.0 (Mac OS X 0.0.0): Executed 2 of 2 (1 FAILED) (0 secs / 0.242 secPhantomJS 2.0.0 (Mac OS X 0.0.0): Executed 2 of 2 (1 FAILED) (0.054 secs / 0.242 secs)

最佳答案

对于 Jhon Papa 风格,您不需要使用 $new 创建 scope。在创建 Controller 时只需传递 {} 而不是 $scope

并将 Controller 初始化放在beforeEach内;

    beforeEach(inject(function(_$controller_, _StorageFactory_,      _$rootScope_) {
AlertsController = _$controller_;
StorageFactory = _StorageFactory_;
AlertsController('AlertsController', {} });
}));

it("creatAlert should be defined",function(){

expect(AlertsController.creatAlert ).toBe(true);
})

关于angularjs - 如何根据 john papa 风格指南在 angularjs 中编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39345527/

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