【问题标题】:Jasmine doesn't inject servicesJasmine 不注入服务
【发布时间】:2016-02-11 10:59:46
【问题描述】:

前提:我的应用程序运行良好,但无论如何我决定实施单元测试。 我的测试,检查服务给定对象是否定义失败。

这是我的服务代码:

//app/components/lib/search.js
angular.module("search", ["lazyLoad", "httpInterceptor"])

.service("SearchObject", ['$rootScope', '$location', 'Globals', function ($rootScope, $location, Globals) {
        'use strict';
        var obj,
            SearchObjectPrototype = {};

        SearchObjectPrototype.clone = function (source) {
            var prop;

            for (prop in this) {
                if (this.hasOwnProperty(prop)) {
                    this[prop] = source[prop] || null;
                }
            }
        };

        //Definizione SearchObject
        obj = Object.create(SearchObjectPrototype, {
            q : {value: null, writable: true, enumerable: true},
            max_id : {value: null, writable: true, enumerable: true},
            next_results : {value: null, writable: true, enumerable: true},
            query_debug : {value: null, writable: true, enumerable: true}
        });

        Object.preventExtensions(obj);                      

        this.getInstance = function () {
            return obj;
        };
    }])

这是我的测试代码:

console.log(1);
describe('search module', function() {
    console.log(2);
    beforeEach(module('search'));

    describe('SearchObject test', function() {
        console.log(3);
        var SearchObject;

        beforeEach(inject(function(_SearchObject_){
            console.log(4);
            // The injector unwraps the underscores (_) from around the parameter names when matching
            SearchObject = _SearchObject_;
        }));

        it('should evaluate the injected SearchObject', function (){
            console.log(5);
            expect(SearchObject).toBeDefined()
        });
    });    
});

这是我的 karma.conf.js

// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-10-20 using
// generator-karma 1.0.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    // as well as any additional frameworks (requirejs/chai/sinon/...)
    frameworks: [
      "jasmine"
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-ui-router/release/angular-ui-router.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
      'bower_components/Chart.js/Chart.js',
      'bower_components/angular-chart.js/dist/angular-chart.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      "app/components/lib/search.js",
//      "test/mock/**/*.js",
      "test/spec/search.js"
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 8080,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
      "PhantomJS"
    ],

    // Which plugins to enable
    plugins: [
    "karma-chrome-launcher",
      "karma-phantomjs-launcher",
      "karma-jasmine"
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
    //   '/': 'http://localhost:9000/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};

这是我的 Karma 输出

Running "karma:unit" (karma) task
11 02 2016 11:55:43.447:INFO [karma]: Karma v0.13.19 server started at http://lo
calhost:8080/
11 02 2016 11:55:43.474:INFO [launcher]: Starting browser PhantomJS
11 02 2016 11:55:46.510:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on s
ocket /#OphIJTNigEfxY1NIAAAA with id 56068342
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 1

PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 2

PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 3

LOG: 5
PhantomJS 2.1.1 (Windows 8 0.0.0) test sul modulo search SearchObject test shoul
d evaluate the injected SearchObject FAILED
        C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/angular.j
s:4459:53
        forEach@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/a
ngular.js:340:24
        loadModules@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angul
ar/angular.js:4419:12
        createInjector@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/an
gular/angular.js:4344:22
        workFn@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular-mo
cks/angular-mocks.js:2428:60
        **Expected undefined to be defined.**
        C:/Users/Rick/Sviluppo/socialsider-fe/test/spec/search.js:19:45
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.043 se
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.019 secs
/ 0.043 secs)

如您所见,log(4)SearchObject 分配的同一块中没有被调用。对象未定义,测试失败。

谁能解释我为什么?可能是依赖问题?

【问题讨论】:

  • 请添加搜索模块脚本。也服务小sn-p
  • 你粘贴了完整的业力配置文件吗?
  • 尝试将beforeEach(module('search')) 放在嵌套的describe() 中。我认为这应该有效。我有一个类似的问题。如果这不能解决您的问题,请尝试使用 $injector 注入服务

标签: javascript angularjs unit-testing karma-jasmine


【解决方案1】:

我发现你需要自己注入你的服务/工厂:

    beforeEach(function() {
        module('search'));
        inject(function(_SearchObject_) {
            SearchObject = _SearchObject_;
        });
    });

这应该使该服务可用于测试。我刚回去抽查了一些我自己的测试,发现这是我所有的工厂和服务测试的共同点。

更新: 经过进一步审查,这里发生了一些非常奇怪的事情,并且可能需要解决多个问题。我没有你所有的依赖库,如果不模拟或删除lazyLoad和httpInterceptor,角度模块根本不会在测试中加载。我将假设这不是您的问题,并且模块会加载。之后,一旦我模拟出 Globals,它就可以正常加载了。

因此,简而言之,请确保您正确地为测试提供了lazyLoad、httpInterceptor 和 Globals,无论是使用实际代码还是通过模拟,并且测试通过。至少对我来说是这样。

【讨论】:

  • 原来如此。我不得不切换到 Chrome 才能看到它。自从升级到 El Capitan 后,Safari 给我带来了各种渲染问题。
  • 我必须更多地了解每个项目的真正用途。您的某个库可能已经提供了lazyLoad 和 httpInterceptor。 Globals 很可能是您的问题。您可以通过从服务定义中删除它来轻松测试它。无论如何,您的服务现在不使用它,因此只需将其修剪为具有 rootScope 和位置并查看它是否通过。
  • 我尝试了一个 foo 模块和一个专门创建的测试服务,一切正常。这是一个依赖问题。谢谢
猜你喜欢
  • 2013-08-30
  • 2017-05-25
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
相关资源
最近更新 更多