BugHunterUK
BugHunterUK

Reputation: 8948

Testing async/await method. Exception not being caught by Jest in unit test

I'm attempting to test some code that uses await and async using Jest. The problem I'm having is an exception is thrown, but Jest doesn't seem to catch it.

For example, here is run method that checks to see if session.url is present. If not, an exception is thrown:

const args = require('args');
const fs = require('fs');
const { promisify } = require('util');

const readFile = promisify(fs.readFile);

// Loads JSON configuration file
module.exports.loadConfigFile = async (filename) => {
  const contents = await readFile(filename, 'utf8');
  return JSON.parse(contents);
};

// Prepare session ensuring command line flags override config
module.exports.prepareSession = async (flags) => {
  if(!flags.config) return flags;
  const config = await this.loadConfigFile(flags.config);
  return {...config, ...flags};
};

// Runs the race application
module.exports.run = async (flags = {}) => { 
  const session = await this.prepareSession(flags);
  if(!session.url) throw new Error('A valid URL is required');
};

Here I test to see if an exception is thrown:

describe('Race Module', () => {
  test('Throws exception if no URL is provided', async () => {
    const runner = await race.run();
    expect(runner).toThrowError();
  });

  ...

The test runs and it appears an exception is thrown but jest hasn't caught it and it doesn't pass:

Race Module
    ✕ Throws exception if no URL is provided (3ms)

● Race Module › Throws exception if no URL is provided

A valid URL is required

  at Object.<anonymous>.module.exports.run (src/race.js:23:27)
      at <anonymous>

Any ideas where I'm going wrong?

My initial thought was to chain catch(() => {}) to race.run() in the test but I am not entirely sure how I would test that. That might not even be the problem.

Upvotes: 0

Views: 1202

Answers (1)

BugHunterUK
BugHunterUK

Reputation: 8948

The fix was to use rejects.toThrow. But, note that this functionality is currently broken in master. I had to use a beta branch. See here: https://github.com/facebook/jest/pull/4884

test('Throws exception if no URL is provided', async () => {
    await expect(race.run())
      .rejects
      .toThrow('A valid URL is required');
});

Upvotes: 2

Related Questions