我有课:
export class MyClass {
public async get(name: string): Promise<string> {
if(name == "test") throw new Error("name is eql 'test'");
// do something
}
}我想要检查函数get expects抛出。
expect(myClass.get.bind(parser, "test")).to.throw("name is eql 'test'");但它不起作用。它是如何修复的?
发布于 2020-04-22 12:18:14
如果您只使用chai,则chai不支持在异步函数中抛出assert error。相反,您可以使用try/catch + async/await。另一种方法是使用chai-as-promised插件。
例如。
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
----------|---------|----------|---------|---------|-------------------https://stackoverflow.com/questions/61342139
复制相似问题