Reputation: 1264
I've this function which takes email and access Key as parameters and make a network call to mailboxlayer api, and returns a promise with validation result.
function validateEmail(email, accessKey) {
return new Promise(function (fulfill, reject) {
request.get("http://www.apilayer.net/api/check?access_key=" +
accessKey + "&email=" + email + "&smtp=1&format=1")
.end(function (err, res) {
if (err) {
reject(err);
}
else {
fulfill(res.body);
}
});
});
}
I want to test this, So I've created a following test
describe('EmailValidator', function() {
it("Should take an email,accessKeys as parameters and return a Promise",
function() {
const data = {
email: "somemail@gmail.com",
did_you_mean: "",
user: "somemail",
domain: "gmail.com",
format_valid: true,
mx_found: true,
smtp_check: true,
catch_all: null,
role: false,
disposable: false,
free: true,
score: 0.8
};
obj.validateEmail("somemail@gmail.com","80867a1cafc7017cd9a9b510c01d1ba7")
.then(value => {
expect(data).toEqual(value);
})
});
});
And I get the result "Successful test" with the following screen
But then to get the failed result, in the data object(which I've used to compare with the result I get from the network call), I just changed the user value from user: "somemail" to user: "anothermail".
So Here I'm expecting the test to be failed since the object I'm comparing is different than the object I'm getting from the network. But the result is not as expected but the test getting passed with some suggestions. Result shown in the picture below
I wanted to know what's is happening here and How can I achieve this to work as I expected i.e get this test to be failed.
Upvotes: 0
Views: 123
Reputation: 11340
The problem is that your test finishes before the promise produces the error. To test in Jest using promises you need to return the promise from the test. Doing that will make the test to wait until the promise is completed and the test would fail if the promise rejected.
Simply add a return
statement to your test, try this -
return obj.validateEmail("somemail@gmail.com","80867a1cafc7017cd9a9b510c01d1ba7")
.then(value => {
expect(data).toEqual(value);
})
});
From the Jest docs -
Be sure to return the promise - if you omit this return statement, your test will complete before Promise method completes.
Upvotes: 2