我正在测试AngularJS服务,作为其中的一部分,我想确保永远不会调用某个回调。现在,我的测试看起来像
it('should succeed to login the user', function () {
var params = {
email: 'foo@bar.com',
password: 'hunter2'
};
var member = {
remoteAddress: '1.2.3.4'
};
$httpBackend.expectPOST(fakeApiUrl + '/1/authentication/login', params)
.respond(200, member);
auth.login(params.email, params.password).then(
function (m) {
expect(m.remoteAddress).toBe(member.remoteAddress);
},
function () {
// I want this to be fail()
expect(true).toBe(false);
}
);
$rootScope.$digest();
$httpBackend.flush();
});
问题是,为了在触发回调时使测试失败,我必须做一些像expect(true).toBe(false)
那样脏的事情。
有没有更好的方法来实现这一目标?例如,我可以使用更合适的匹配器,还是应该以不同的方式构建我的测试?
答案 0 :(得分:1)
it('should succeed to login the user', function () {
var params = {
email: 'foo@bar.com',
password: 'hunter2'
};
auth.login = jasmine.createSpy().andReturn($q.reject());
auth.login(params.email, params.password).then(
function (m) {
expect(m.remoteAddress).toBe(member.remoteAddress);
},
function () {
// I want this to be fail()
expect(true).toBe(false);
});
$scope.$digest();
});
答案 1 :(得分:1)
这样做的一种方法是创建一个间谍并断言间谍从未被调用过......
var mySpy = jasmine.createSpy('mySpy');
$httpBackend.expectPOST(fakeApiUrl + '/1/authentication/login', params)
.respond(200, member);
auth.login(params.email, params.password).then(
function (m) {
expect(m.remoteAddress).toBe(member.remoteAddress);
},
mySpy
);
$rootScope.$digest();
$httpBackend.flush();
expect(mySpy).not.toHaveBeenCalled();