【发布时间】:2018-04-24 21:29:50
【问题描述】:
我正在尝试使用 Jasmine 为 Angular 服务创建一个简单的单元测试。 但是当我通过 Karma 运行测试时,我收到以下错误:
Failed to instantiate module app
而且我不知道为什么会出现此错误。我用谷歌搜索并尝试应用以下解决方案。但没有一个奏效。
- 我尝试更改 karma.conf.js 中的文件顺序。
- 我尝试以不同的方式编写单元测试。我的意思是以不同的方式注入服务。
但错误依旧。
这是一个非常简单的代码。请在下面找到代码以供参考:
string.service.js
(function () {
"use strict";
angular
.module('app')
.factory("stringService", stringService)
function stringService() {
return {
checkForAlphaNumeric: checkForAlphaNumeric,
};
function checkForAlphaNumeric(string) {
var regex = /^[a-zA-Z0-9]+$/;
return regex.test(string);
}
}
})();
string.service.spec.js
describe("-----> String Service", function () {
var stringService;
beforeEach(function () {
angular.mock.module('app');
inject(function ($injector) {
stringService = $injector.get('stringService');
});
});
it("--> stringService should be Defined.", function () {
expect(stringService).toBeDefined();
});
});
karma.conf.js
// list of files / patterns to load in the browser
files: [
//External
'./node_modules/angular/angular.js', // Angular Framework
'./node_modules/angular-mocks/angular-mocks.js', // Loads the Module for Tests
'./node_modules/@uirouter/angularjs/release/angular-ui-router.js', // UI-Router
'./node_modules/angular-route/angular-route.js',
//Sub Modules
'./app/authentication/authentication.module.js',
//Main Module
'./app/app.module.js', // Angular App
//Controllers
'./app/authentication/login.controller.js',
//Services and Factories
'./app/services/string.service.js',
//Specs
'./app/licensing/licensing.controller.spec.js',
'./app/services/string.service.spec.js'
],
- 交换模块和子模块引用也不起作用。
- 将模块和子模块引用放在控制器和服务之前或之后也不起作用。
任何帮助将不胜感激。
【问题讨论】:
标签: angularjs jasmine karma-runner karma-jasmine