dimanche 18 août 2019

Testing a rejected promise with Ava

I have a function readFile() that returns a promise as below:

function readFile(path) {
    return new Promise(function(resolve, reject){
        fs.access(path, fs.F_OK, (err) => {
            if(err){
                console.log('Will throw error now!');     //--> test
                reject('data.json file does not exist'); //--> test
            }

            fs.readFile(path, (err, data) => {
                if(err) throw err;
                resolve(data);
            });
        });
    })
}

To bump up the code coverage numbers, I intend to test the err statements marked above. I have written the ava test for the same as below:

test('Check if error is thrown', async t => {
    var ans = await fileReader.readFile('./tests/tests.json');
    t.is('data.json file does not exist', ans);
});

Now the file ./tests/tests.json does not intentionally exist since I want to test the reject(); but I get the following error:

Will throw error now!
✖ Check if error is thrown Rejected promise returned by test

Uncaught exception in tests/readFile.test.js

Error: ENOENT: no such file or directory, open './tests/tests.json'

✖ tests/readFile.test.js exited with a non-zero exit code: 1

1 test failed
1 uncaught exception

Check if error is thrown

Rejected promise returned by test. Reason:

'data.json file does not exist'

npm ERR! Test failed. See above for more details.

How do I resolve this error?

Thanks!

Edit: In case it matters, I am using NYC for code coverage.

Aucun commentaire:

Enregistrer un commentaire