本文介绍了由$ httpBackend与测试$资源服务的一个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我想念的东西。已经花了一些时间试图了解为什么我的测试是行不通的。

I guess I miss something. Have spent some time trying to understand why my test is not working.

在code。

angular.module('services')
    .factory('UserPreferencesService', ['$resource', function ($resource)
    {
        return $resource('/rest/user-preferences/:id', {},
        { getById: { method: "GET", params: { id:'@id'}} });

    }
]);

测试:

it('should get by Id', function() {
    //given
    var preferences = {language: "en"};

    httpBackend.whenGET('/rest/user-preferences/1').respond(preferences);

    //when
    service.getById( {id:1} ).$promise.then(function(result) {

        console.log("successssssssssssssssssssssssssssssssssssss");

     //then
     expect(result).toEqual(preferences);
    }, function() {
        console.log("something wrong");
    })
});

它永远不会触发:successssssssssssssssssssssssssssssssssssss。

It never triggers: "successssssssssssssssssssssssssssssssssssss".

我错过了什么?

推荐答案

有一些事情错了,其他的东西在你的code失踪。

There were some things wrong and other things missing in your code.

主要的问题是,你是不是要求仿效来自服务器的响应刷新()功能,所以 $承诺未曾解决。另外,请记住,当诺言得到解决,那你得到它是一个承诺,这意味着回应是这样的:预期(结果).toEqual(preferences); 将无法正常工作,但这:预期(result.lang).toEqual(preferences.lang);

The main problem was that you were not calling the flush() function that emulates the response from the server, so the $promise was never resolved. Also, bear in mind that when the promise gets resolved, the response that you get it's a promise, meaning that this: expect(result).toEqual(preferences); won't work, but this: expect(result.lang).toEqual(preferences.lang); will.

在这里,你有你的code的一个固定的版本:

Here you have a fixed version of your code:

该服务:

angular.module('services',['ngResource'])
    .factory('UserPreferencesService', ['$resource', function ($resource)
    {
      return $resource('/rest/user-preferences/:id', {},
        { getById: { method: "GET", params: { id:'@id'}} });
    }
]);

测试:

describe('My Suite', function () {
  var httpBackend, service;
  beforeEach(module('services'));

  beforeEach(inject(function (_$httpBackend_, UserPreferencesService) {
      httpBackend = _$httpBackend_;
      service = UserPreferencesService;
  }));

  describe('My Test', function () {
      it('should get by Id', function() {
        var preferences = {language: "en"};
        var result = {};

        httpBackend.whenGET('/rest/user-preferences/1').respond(preferences);

        service.getById({id:1}).$promise.then(function(result_) {
          result = result_;
        });

        expect(result.language).not.toEqual(preferences.language);

        httpBackend.flush();

        expect(result.language).toEqual(preferences.language);
    });
  });
});

这篇关于由$ httpBackend与测试$资源服务的一个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 15:19