对,按照 jl 的建议,我最终得到了这段代码,效果很好。显然,我的 javascript 知识是一个缺陷,我并没有真正考虑到这一切都存在于全球地址空间中的事实。
首先,我创建一个文件“base_controller.spec.js”。在这个文件中,我声明了一个全局对象:
var BaseController =
{
baseBeforeEach: function() {
// mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('bProject'));
// create the custom mocks on the root scope
beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_, SidebarService, $state, BreadcrumbService ){
//create an empty scope
scope = $rootScope.$new();
scope.$rootScope = $rootScope;
scope.$state = $state;
scope.breadcrumb = BreadcrumbService;
// we're just declaring the httpBackend here, we're not setting up expectations or when's - they change on each test
scope.httpBackend = _$httpBackend_;
// setup the project id to a known value
scope.setupSidebar = SidebarService.sidebar;
scope.setupSidebar.projectId = 2;
}));
},
baseAfterEach: function() {
afterEach(function() {
scope.$digest();
scope.httpBackend.verifyNoOutstandingExpectation();
scope.httpBackend.verifyNoOutstandingRequest();
});
}
};
然后,我只在测试中使用 BaseController:
describe( 'Risk functionality.', function() {
BaseController.baseBeforeEach();
BaseController.baseAfterEach();
describe( 'Risks list controller.', function() {
这个例子相当简单,尽管在每个控制器上都有模拟标准很好。但是我对每个控制器都有一套标准测试,这种方法可以让我做到。
需要注意的是 karma 配置中包含的顺序 - 您需要尽早包含此文件,否则某些模块无法看到它。
我会给 jl 一个赞成票,但这是一个评论,所以我不能!