[英]Testing Angular Modules with Jasmine Unit Tests
我在我的應用程序中使用AngularJS服務。 我了解到我創建的服務不可靠。 因此,我想圍繞它構建一些單元測試。 雖然該服務在我的AngularJS應用程序中可以正常工作,但在使其與Jasmine一起使用時遇到了問題。 就像我無法加載任何模塊。 我已經將代碼精簡了。 我不明白我在做什么錯。 我的代碼如下所示:
myService.js
'use strict';
angular.module('customModule', [])
.factory('$serviceName', [function () {
return {
isAvailable: function () {
return true;
}
};
}]
);
myService.spec.js
describe('customModule', function() {
beforeEach(function() {
console.log('loading module...');
module('customModule');
});
describe('$serviceName', function () {
var myService = null;
beforeEach(inject(function ($serviceName) {
console.log('loading service...');
myService = $serviceName;
}));
it('should work', function () {
console.log('testing');
var isAvailable = myService.isAvailable();
console.log(isAvailable);
expect(1 + 2).toEqual(3);
});
});
})
gruntfile.js
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jasmine: {
unitTests: {
src: 'test/*.js',
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['jasmine:unitTests']);
};
我的茉莉花測試正在運行。 但是,未加載類似myService.js的文件。 我不確定該怎么做。 我也不確定如何在測試中獲得“角度”(在myService.js中使用)。
謝謝您的幫助。
您是否在myService.spec.js中加載了Angular應用程序? 否則,$ serviceName不可用於依賴項注入。
您應該在測試文件中添加以下內容:
beforeEach(module('angularApp'));
(當然,將angularApp替換為您使用的名稱)
另外,最好使用另一個beforeEach塊來處理依賴項注入,以便可以在myService.spec.js中的所有測試中使用它。 總的來說,您應該有以下內容:
describe('serviceName', function () {
beforeEach(module('angularApp'));
var iMyService
// Initialize the service
beforeEach(inject(function ($serviceName) {
iMyService = $serviceName;
}));
it('should check if available', function () {
var isAvailable = iMyService.isAvailable();
console.log(isAvailable);
expect(1 + 2).toEqual(3);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.