Expect expression not to throw any error using Chai

Viewed 106

I have a function

export function getFileContent(path: string): any {
    const content = readFileSync(path);
    return JSON.parse(content.toString());
}

If I want to check if the expression getFileContent(meteFile) throws some definite error I should write something like

expect(getFileContent(meteFile)).to.throw(new SyntaxError('Unexpected token } in JSON at position 82'));

But is there a way to check if the expression doesn't raise any error?

I tried this

expect(getFileContent(metaFile)).not.to.throw(); 

But got the error

AssertionError: expected { Object (...) } to be a function

So how can I check if the function call doesn't throw any error?

2 Answers

You can check if the function call doesn't throw an error using assert.doesNotThrow method

Here is an example from the documentation

assert.doesNotThrow(fn, 'Any Error thrown must not have this message');
assert.doesNotThrow(fn, /Any Error thrown must not match this/);
assert.doesNotThrow(fn, Error);
assert.doesNotThrow(fn, errorInstance);

For further understanding checkout it's documentation: assert.doesNotThrow

It seems like you are using expect, so then you can use expect(fn).to.not.throw to make sure it doesn't throw an error.

expect(myFn).to.not.throw(); // makes sure no errors are thrown
expect(myFn).to.not.throw(SomeCustomError, "the message I expect in that error"); // not recommended by their docs

You should probably look at the docs for this.

Related