Home > Blockchain >  How to test throw error in error event using Jest
How to test throw error in error event using Jest

Time:10-02

I have a problem with that learning case. I have the following code and I want to test the throwing error:

export const someFunction = async () => {
//...
const fileReadStream = createReadStream(absoluteFilePath)
    .on('error', err => {
        throw new Error(`Failed file stream creation, file: '${absoluteFilePath}', reason: ${err.message}`);
    });
//...
};

Test:

test('should throw error ', async () => {
    await expect(someFunction())
        .rejects
        .toThrowError(/Failed file stream creation, file: .*, reason: .*/);
});

CodePudding user response:

Throwing an exception inside an async callback will not throw the exception from the original invocation. You'll want to use your own Promise.

export const someFunction = async () => {
  return new Promise((resolve, reject) => {
    //...
    // Track errors (not sure if close is called after an error event)
    let hasError = false;
    const fileReadStream = createReadStream(filePath)
      .on('error', err => {
        hasError = true;
        reject(new Error(`Failed file stream creation, file: '${absoluteFilePath}', reason: ${err.message}`));
      })
      .on('close', () => {
        if (!hasError) {
          resolve(whateverFinalResult);
        }
      });
    //...
  });
};

We generally don't expect promise functions to resolve, reject AND potentially throw an error. This approach hooks into the expected resolve or reject, not other return or throws. Your test remains the same. Even though jest makes it sound like an error was thrown, it was technically a Promise rejection.

  • Related