【发布时间】:2017-04-17 21:18:56
【问题描述】:
Angular 单元测试的新手。我已经阅读了大量有关间谍、存根和模拟的内容,但在执行基础知识时遇到了很多麻烦:
- 我的控制器是否正确接收我传递给构造函数的服务?
- 是否在实例化时调用
initializePage?
Controller.spec(很确定以下是必需的)
'use strict';
describe('Controller: MainController', function() {
// load the controller's module
beforeEach(module('myApp'));
var MainController, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
MainController = $controller('MainController', { $scope: scope });
}));
规范的其余部分:
it('should have called initializePage', function() {
var spyInstance = sinon.spy(MainController, "initializePage");
assert(spyInstance.called, "initializePage() was not called once");
});
});
我一直认为间谍就足够了,但我不确定MainController 是否正在被处决。目前spyInstance 抛出错误。 这里需要存根吗?为什么?
控制器
class MainController {
constructor($scope, $http, $state, Session) {
this.$scope = $scope;
this.$state = $state;
this.Session = Session;
this.initializePage();
}
initializePage() {
//blah blah
}
谢谢。
修订: main.controller.spec.js
describe('Controller: MainController', function() {
// load the controller's module
beforeEach(module('scriybApp'));
var mainControllerInstance, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
mainControllerInstance = $controller('MainController', { $scope: scope });
}));
it('should test the controller is in order', function() {
assert.isFunction(mainControllerInstance.$onInit, "$onInit() has not been defined");
sinon.spy(mainControllerInstance, "$onInit");
assert(mainControllerInstance.$onInit.called, "$onInit() called = false");
});
});
【问题讨论】:
标签: angularjs unit-testing ecmascript-6 sinon chai