我有以下我想测试的工厂:
angular
.module('enigma.authFactory', [])
.factory('authFactory', authFactory);
authFactory.$inject = ['$http'];
function authFactory($http){
function doesUserExist(email){
return $http.post('/doesUserExist', email)
.success(function(data){
if(data !== 'user exists'){
return false;
} else {
return true;
}
});
}
}
所以我写了以下测试:
describe('Auth Service Tests', function() {
var $httpBackend, defer, doesUserExistReqHandler;
beforeEach(inject(function(_$httpBackend_, $injector, $q) {
$httpBackend = _$httpBackend_;
defer = $q.defer();
doesUserExistReqHandler = $httpBackend.when('POST', '/doesUserExist').respond(defer.promise);
}));
describe('authFactory.doesUserExist()', function() {
it('should return true is a user exists', function() {
user = {
email: 'bwayne@wayneenterprise.com'
};
$httpBackend.whenPOST('/doesUserExist', user).respond('user exists');
var doesUserExist = authFactory.doesUserExist(user);
$httpBackend.flush();
expect(doesUserExist).toEqual(true);
});
});
});
我检查了authFactory.doesUserExist函数,我正确地将数据集设置为'user exists',它将函数路由返回true。但是在单元测试中,authFactory.doesUserExist被设置为以下对象。
Expected Object({ $$state: Object({ status: 1, pending: undefined, value: Object({ data: Object({ $$state: Object({ status: 0 }) }), status: 200, headers: Function, config: Object({ method: 'POST', transformRequest: [ Function ], transformResponse: [ Function ], paramSerializer: Function, url: '/doesUserExist', data: Object({ email: 'bwayne@wayneenterprise.com' }), headers: Object({ Accept: 'application/json, text/plain, */*', Content-Type: 'application/json;charset=utf-8' }) }), statusText: '' }), processScheduled: false }), success: Function, error: Function }) to equal true.
我认为问题是测试没有正确解析承诺,所以我在authFactory.doesUserExist返回true之前设置了res变量。
我将如何解决这个问题?
答案 0 :(得分:1)
因此,需要执行一些操作才能使代码与您拥有的内容一起使用。
以下是演示http://plnkr.co/edit/4GvMbPJgc0HcJcgFZ4DL?p=preview
在测试中
$httpBackend.when('POST', '/doesUserExist').respond(defer.promise);
,因为它没有完成任何事情,实际上它在其他$httpBackend.whenPost
中感到困惑。authFactory.doesUserExist(user)
会返回一个promise。 代码:
var doesUserExist = authFactory.doesUserExist(user)
.then(function (data) {
responseData = data;
});
$httpBackend.flush();
expect(responseData).toEqual(true);