In scenarios where only utilizing chai
, assertions for errors thrown in asynchronous functions are not supported. One workaround is to employ try/catch
along with async/await
. Another option is to integrate the chai-as-promised plugin.
For instance:
index.ts
:
export class MyClass {
public async get(name: string): Promise<string> {
if (name === 'test') {
throw new Error("name is eql 'test'");
}
return '';
}
}
index.test.ts
:
import { MyClass } from './';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
describe('61342139', () => {
it('should pass', async () => {
const myClass = new MyClass();
try {
await myClass.get('test');
} catch (error) {
expect(error).to.be.instanceOf(Error);
expect(error.message).to.be.equal("name is eql 'test'");
}
});
it('should pass too', async () => {
const myClass = new MyClass();
await expect(myClass.get('test')).to.be.rejectedWith("name is eql 'test'");
});
});
The unit test results along with a coverage report:
61342139
✓ should pass
✓ should pass too
2 passing (12ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 75 | 50 | 100 | 75 |
index.ts | 75 | 50 | 100 | 75 | 6
----------|---------|----------|---------|---------|-------------------