I want to test my promise function to load an image, the piece of code looks like this:
function imagePromise() {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(true));
img.addEventListener('error', () => reject(false));
img.src = 'http://78.media.tumblr.com/tumblr_lr9mx5Axur1qlyuwso1_1280.jpg';
});
}
When I consume my promise in the browser, it works fine:
imagePromise().then((result) => console.log(result));
// fulfill the promise and log the result: true
However, when I'm testing my promise using ava and browser-env, ava returns an error:
Promise returned by test never resolved
My test file looks like this:
import test from 'ava';
function imagePromise() {
return new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(true));
img.addEventListener('error', () => reject(false));
img.src = 'http://78.media.tumblr.com/tumblr_lr9mx5Axur1qlyuwso1_1280.jpg';
});
}
test('load image with promise', (t) => {
return imagePromise().then((result) => {
t.is(result, true);
});
});
Note that I have both tried addEventListener
and onload
/onerror
methods due to browser compatibility, and browser-env have been configured to work with ava. Is there something I'm missing?