Mocking resolve in state using Jasmine & Angular

2019-09-10 23:15发布

I'm trying to mock the resolve functions inside the $state of my ui-router file, but I can't seem to get it to work. Here's my router code:

$stateProvider
.state('state.of.page', {
  url: '/url-to-page',
  template: require('./page-template.html'),
  controller: 'PageCtrl',
  controllerAs: 'page',
  resolve: {
    /**
     * Cloning of page object in case user leaves page 
     * without saving
     */
    pageObjClone: ['pageObj', function (pageObj) {
      return angular.copy(pageObj);
    }],
    pageTemplate: ['template', function (template) {
      return template;
    }]
}

Here is my Jasmine code. I'm currently getting the error 'fn' is not a function when I run the test.

'use strict';

describe('my jasmine $state test', function() {

  var $state;
  var $injector;
  var stateName = 'state.of.page';
  var stateObj;

  beforeEach(function() {

    angular.mock.module('MyApp');

    inject(function(_$rootScope_, _$state_, _$injector_) {
      $state = _$state_;
      $injector = _$injector_;

      stateObj = {
        customerObjClone: ['customerObj', function (customerObj) {}],
        template: ['template', function (template) {}]
      };
    });
  });

  it('should resolve data', function() {
    var state = $state.get(stateName);
    expect($injector.invoke($state.resolve)).toBe('stateObj');
  });
});

Thanks for any help.

1条回答
女痞
2楼-- · 2019-09-10 23:32
  ...
  var pageObj, template;

  beforeEach(function() {

    angular.mock.module('MyApp');

    inject(function(..., _pageObj_, _template_) {
      ...
      pageObj = _pageObj_;
      template = _template_;
    });
  });

  it('should resolve data', function() {
    var state = $state.get(stateName);
    expect($injector.invoke(state.resolve.pageObjClone)).toEqual(pageObj);
    expect($injector.invoke(state.resolve.pageTemplate)).toBe(template);
  });

Depending on how complex resolvers and their dependencies are, the dependencies may be mocked and injected into resolver, e.g.

expect($injector.invoke(state.resolve.pageTemplate, null, { template: mockedTemplate }))
  .toBe(mockedTemplate);
查看更多
登录 后发表回答