Lucas Almeida Carotta
Lucas Almeida Carotta

Reputation: 567

How to compare ENOENT error in Jest?

I have the following function:

export const readAsync = (filename: string): Promise<object> =>
    new Promise((resolve: (data: object) => void, reject: (data: Error) => void) => {
        readFile(join(__dirname, `../../__mocks__/${filename}`), 'utf8', (err: Error, data: string) => {
            if (err) {
                reject(err);
            } else {
                resolve(JSON.parse(data));
        }
    });
});

That I had wrote in TypeScript and I'm testing it in ts-jest through:

describe('Testing readAsync function', () =>
    test('filename \"undefined\".', () => {
        const filePath: string = join(__dirname, '../../__mocks__/undefined');
        const errorMessage: Error = new Error(`ENOENT: no such file or directory, open \'${filePath}\'`);
        expect.assertions(1);

        return expect(readAsync(undefined)).rejects.toMatchObject(errorMessage);
});

But this give me this error:

expect(received).toMatchObject(expected)

Expected value to match object:
  [Error: ENOENT: no such file or directory, open '/home/farm/Documents/podsearch_bot/__mocks__/undefined']
Received:
  [Error: ENOENT: no such file or directory, open '/home/farm/Documents/podsearch_bot/__mocks__/undefined']
Difference:
Compared values have no visual difference.

I, sincerlly think, that must be a matcher option, but right know I've tested with:

But none seem to work... How can I fix this?

Upvotes: 2

Views: 1855

Answers (2)

Ida Amit
Ida Amit

Reputation: 1687

test('Should return an error', async () => {
   expect(async() => await readAsync('./nomatch/nomatch.txt')).toThrow('ENOENT: no such file or directory, open \'./nomatch/nomatch.txt\'');
   expect(async() => await readAsync('./nomatch/nomatch.txt')).toThrow(/^ENOENT.*/g);
});

When you pass an arrow function as a perameter to expect, jest executes the function.

Upvotes: 0

Fabien Greard
Fabien Greard

Reputation: 1894

One way to make it work is to catch the error and compare the code it returns, using your example:

  test('Should return an error', async () => {
    try {
      await readAsync('./nomatch/nomatch.txt');
    } catch (e) {
      expect(e.code).toEqual('ENOENT');
    }
  });

JavaScript properties may be non-enumerable, which means they does not appear in for..in loops or Object.keys results.

You may want to know wich key are available on the Error object with Object.getOwnPropertyNames(e)

Upvotes: 3

Related Questions