Angularjs 使用承诺模拟HTTP响应并返回虚拟数据
我正在调用一个API服务,它从工厂返回一个承诺 这是我工厂的一部分Angularjs 使用承诺模拟HTTP响应并返回虚拟数据,angularjs,unit-testing,mocking,jasmine,Angularjs,Unit Testing,Mocking,Jasmine,我正在调用一个API服务,它从工厂返回一个承诺 这是我工厂的一部分 factories.factory('OnBoardingFactory', ['$http', function ($http) { var dataFactory = {}; dataFactory.get = function (url) { return $http.get('http://localhost/api/onbo
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).tohavebeincall()时如果调用了code>,则可以正常通过。然而,当我运行expect(scope.status).toBe(200)
时,它打破了“Expected undefined to be 200”
这表明我的FakeOnBoardingFactory没有返回任何数据。但我似乎找不到问题所在。一定是支持多主体断言的更改导致了此错误。
目前的解决方法是不使用expect,而是在结束函数回调中执行断言。
所以不是。预计(200)个
end(function(err,res) { res.status.should.equal(200) },
或者如果您确实使用expect。。您需要确保指定一个主体以及一个状态
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;
});
})