【问题标题】:mock HTTP response with promises and return dummy data使用 Promise 模拟 HTTP 响应并返回虚拟数据
【发布时间】:2015-07-05 18:01:16
【问题描述】:

我正在调用一个从工厂返回承诺的 API 服务。

这是我工厂的一部分。

     factories.factory('OnBoardingFactory', ['$http',

        function ($http) {

          var dataFactory = {};

          dataFactory.get = function (url) {
            return $http.get('http://localhost/api/onboarding/' + url)
          };

          return dataFactory
        }

     ]);

这是从控制器调用它的地方:

OnBoardingFactory.get('login?username=test&password=password')
   .then(function(response){
      $scope.response = response.status;
   })

这绝对可以很好地返回控制器中的数据。但是,当我来测试它时,我遇到了困难。这是我的测试脚本:

var scope, FakeOnBoardingFactory, controller, q, deferred;

beforeEach(module('app.module'));

beforeEach(function () {
  FakeOnBoardingFactory = {
    get: function () {
      deferred = q.defer();
      // Place the fake return object here
      deferred.resolve({ response: {status: 200}});
      return deferred.promise;
    }
  };
  spyOn(FakeOnBoardingFactory, 'get').and.callThrough();
});

beforeEach(inject(function ($q, $rootScope, $controller, $injector ) {

  scope = $rootScope.$new();
  q = $q;

  controller = $controller(OnBoardingCtrl, {
    $scope: scope,
    OnBoardingFactory: FakeOnBoardingFactory
  })

}));

it('Should call the form and return 200', function () {

  // Execute form
  scope.loginCredentials({$valid: true});

  scope.$apply();

  // Ensure script is called (which passes fine)
  expect(FakeOnBoardingFactory.get).toHaveBeenCalled();

  scope.$apply();

  // BREAKS HERE
  expect(scope.status).toBe(200);

})

expect(FakeOnBoardingFactory.get).toHaveBeenCalled(); 被调用时,一切正常。但是,然后我运行expect(scope.status).toBe(200),它打破了“预期未定义为 200”。

这表明我的 FakeOnBoardingFactory 没有返回任何数据。但我似乎找不到问题。

【问题讨论】:

    标签: angularjs unit-testing mocking jasmine


    【解决方案1】:

    一定是支持多个主体断言的更改导致了这个错误。 现在的解决方法是要么不使用期望,而是在结束函数回调中做你的断言。 所以不是 .expect(200) 而是它。

    end(function(err,res) { res.status.should.equal(200) },
    

    或者如果你确实使用了 expect.. 你需要确保你指定了一个 body 以及一个 status..

    it('should assert status only 1', function(done){ 
    var app = express(); 
    app.get('/user', function(req, res){
     res.send(201, { name: 'tobi' }); }); request(app) .get('/user')
     .expect('Content-Type', /json/)
     .expect('Content-Length', '20')
     .expect(201)
     .end(function(err, res){
     if (err) throw err; 
    }); 
    })
    

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多