Reputation: 12425
I have a test :
it('should not save a user if it already exists', ()=>{
var user : User = {userName : 'jack', name : 'Lenon'};
var user1 : User = {userName : 'jack', name : 'Linon'};
return repository.saveUser(user)
.then((user:User)=>{
return repository.saveUser(user1)
}).then((user : User)=>{
expect('Second ').equals('');
})
.catch((err) =>{
expect(err).equals("A user by that username already exist in the database");
});
});
The idea is to test the repository rejecting to save a second user by the same name. This works, but I am not happy at all with the way I force a failure in the "then". Is there a better way to do that?
Upvotes: 1
Views: 328
Reputation: 92440
If you are trying to assert that the promise is rejected, you can take advantage of the second callback function of then
. If the success callback is called you should throw()
because the test should fail. Then in the second callback which should fire if the promise rejects, you can assert the error value. Something like:
return repository.saveUser(user)
.then((user:User)=> repository.saveUser(user1))
.then((user : User)=> {
// test will fail if promise resolves
throw new Error("Promise should not be fulfilled when user already exists")
},
err => {
// test will pass if promise rejects
// and the expectation is met
expect(err).equals("A user by that username already exist in the database");
}
)
Upvotes: 0
Reputation: 469
Assuming you are using Chai.
Then expect('Second ').equals('');
can become expect.fail();
https://www.chaijs.com/api/bdd/#method_fail
Upvotes: 1