使用Karma工厂从$ resource测试服务

时间:2015-11-18 10:58:53

标签: javascript angularjs unit-testing karma-jasmine angular-resource

我是业力新手,我试图运行测试以检查我的工厂是否设置为API返回的正确值。

apiServices.js:

'use strict';

angular.module('balrogApp.services', ['balrogApp.config'])
  .factory('Requests', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
    return $resource(balrogConfig.backend + '/requests/:id', {id: '@id'});
  }])
  .factory('Projects', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
    return $resource(balrogConfig.backend + '/projects/:id', {id: '@id'}, {'update': { method:'PUT' }});
  }])
  .factory('Users', ['$resource', 'balrogConfig', function($resource, balrogConfig) {
    return $resource(balrogConfig.backend + '/users/:id', {id: '@id'});
  }]);

config.js:

'use strict';

angular.module('balrogApp.config', [])
  .constant('balrogConfig', {
    'backend': 'http://127.0.0.1:8000/api/catalog'
  });

现在,我已经阅读了一些关于资源和业力的文章,但我并没有真正了解如何为我的案例设置单元测试。

这是我的测试文件:(在@Freezystem回答之后编辑)

describe("Services test", function () {
  var Requests, Projects, Users;

  beforeEach(function () {
    angular.mock.module("balrogApp.services");
    angular.mock.inject(function (_Requests_, _Projects_, _Users_) {
      Requests = _Requests_;
      Projects = _Projects_;
      Users = _Users_
    });
  });

  it("API factories must be defined", function () {
    expect(Requests).toBeDefined();
    expect(Projects).toBeDefined();
    expect(Users).toBeDefined();
  });
});

我也用$ httpBackend尝试过一些东西,但是它既不能成功。

如何使这项工作以了解服务是否有效。

另外,如何检查服务是否从API返回预期的响应?

编辑:添加karma.conf.js:

// Karma configuration
// Generated on Tue Nov 17 2015 13:48:48 GMT+0100 (Romance Standard Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
      'bower_components/jquery/dist/jquery.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-aria/angular-aria.js',
      'bower_components/angular-material/angular-material.js',
      'bower_components/angular-messages/angular-messages.js',
      'bower_components/angular-mocks/angular-mocks.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-bootstrap/ui-bootstrap.js',
      'bower_components/ui-select/dist/select.js',
      'bower_components/angular-smart-table/dist/smart-table.js',
      'bower_components/angular-ui-switch/angular-ui-switch.js',
      'bower_components/angular-growl-v2/build/angular-growl.js',
      'bower_components/angular-number-picker/angular-number-picker.js',
      'bower_components/moment/moment.js',
      'app/*.js',
      'app/**/*.js',
      'tests/*.js'
    ],


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


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


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


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher'
    ],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultanous
    concurrency: Infinity
  })
};

到目前为止,我发现了这个错误:http://codepen.io/anon/pen/OyqWdE

1 个答案:

答案 0 :(得分:1)

试着用自己的名字注入每个工厂:

describe("Services test", function () {
  var users, $httpBackend;

  beforeEach(function(){
    angular.mock.module('balrogApp.services');
    angular.mock.inject(function (_Users_, _$httpBackend_) {
      users        = _Users_;
      $httpBackend = _$httpBackend_;
    });
  });

  // clear all outstanding requests after each tests
  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  it("Factories must be defined", function () {
    // simulate API response
    $httpBackend.when('/api/catalog/users/1337')
      .respond( 200, { id : 1337, name : 'Tom' } );

    // there is a better way to do it actually but I'm unable to make it work
    // $httpBackend.whenRoute('GET', '/api/catalog/users/:id')
    //     .respond(function ( method, url, data, headers, params ) {
    //         return [ 200, { user : params.id } ] ;
    //     });

    // make the user request to the API
    var user = users.get({id:1337});
    $httpBackend.flush();

    // test API returned Object
    expect(user.id).toBe(1337);
    expect(user.name).toBe('Tom');
  });
});

如果您有任何其他问题,请告诉我。

相关问题