我有类:
export class MyClass {
public async get(name: string): Promise<string> {
if(name == "test") throw new Error("name is eql 'test'");
// do something
}
}
我想检查函数get是否期望throw。
expect(myClass.get.bind(parser, "test")).to.throw("name is eql 'test'");
但它不起作用。它是如何修复的?
如果只使用chai
,chai不支持在异步函数中抛出断言错误。相反,您可以使用try/catch
+async/await
。另一种方法是使用chai作为承诺的插件。
例如
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'");
});
});
带覆盖率报告的单元测试结果:
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
----------|---------|----------|---------|---------|-------------------