将angular js的service/factory注入到Jasmine中

Injecting angular js service/factory into Jasmine

本文关键字:注入 Jasmine factory angular js service      更新时间:2023-09-26

我正在尝试在我在Angular JS中创建的工厂上运行一些Jasmine单元测试。

这是我的app.js

var app = angular.module('myApp', [
    'ngRoute'
]);

services.js

app.factory('Service', function(){
    var service = {
        one: function(){
            return 1;
          }
      };
    return service;
  })

这是Karma配置文件

  files: [
      'public/bower_components/angular/angular.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'public/js/app.js',
      'public/js/controllers.js',
      'public/js/services.js',
      'test/**/*test.js'
    ],

这是测试

使用严格的;

(function () {
    describe('myApp', function () {
      beforeEach(module('myApp'));
      it('testing the service', inject(function (Service) {
        console.log(Service)
      }));
    });
})();
我真的被困住了,不知道该走哪条路。所有正确的脚本都被加载到浏览器中。此外,应用程序在浏览器中的正常模式下工作,所以服务工厂是好的。

错误信息说:

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
    Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:
    Error: [$injector:nomod] Module 'ngRoute' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

问题正是消息所说的:ngRoute不可用,因为您没有将该脚本包含在Karma配置文件中。您需要在files数组中添加如下一行:

'public/bower_components/angular-route/angular-route.js',

我不知道路径是什么,所以你可能需要调整一下

只是为了帮助一些人,查看setup Karma测试的方式类似于您设置index.html的方式。

在index.html中,你要确保所有你需要的脚本都按正确的顺序加载了。

同样,当你设置Karma时,它需要知道要使用什么脚本。

确保用正确的脚本填充文件部分!

 files: [
      'public/bower_components/angular/angular.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'public/js/app.js',
      'public/js/controllers.js',
      'public/js/services.js',
      'test/**/*test.js'
    ],