How do I get a resource from an Angular.js module for a jasmine test

此生再无相见时 提交于 2019-12-24 13:57:19

问题


I have a module that contains resources for a project, and the code looks like this:

editor_services.js

var editorServices = angular.module('editorServices', ['ngResource']);
editorServices.factory('Project', ['$resource', '$http',function($resource, $http){ 
//...etc

now I would like to write tests for a controller that expects a project resource as an argument. How can I get an instance of the project resource that is created by this factory out of the editorServices variable?


回答1:


Here is a working example how one would test Resources (or http) in angular http://plnkr.co/edit/kK5fDFIVpyZTInH1c6Vh?p=preview

The basic setup is:

  1. load angular-mocks.js in your test. This replaces the $httpBackend with mock version. See: http://docs.angularjs.org/api/ngMock.$httpBackend

  2. In your test call $httpBackend.expect() to create expectation to be mocked out.

  3. When you want to simulate server response call $httpBackend.flush()

  4. There is a caveat that normal .toEqual() from jasmine dose not work with $resource so you have to create custom matcher like so:

  beforeEach(function() {
    this.addMatchers({
      // we need to use toEqualData because the Resource hase extra properties 
      // which make simple .toEqual not work.
      toEqualData: function(expect) {
        return angular.equals(expect, this.actual);
      }
    });
  });


来源:https://stackoverflow.com/questions/16486115/how-do-i-get-a-resource-from-an-angular-js-module-for-a-jasmine-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!