0

我不确定我是否正确理解 chai,但是有没有办法测试一个函数在发送错误数量(或类型)的参数时是否会失败?例如:

expect( function(){
    let foo = new MyClass();
} ).to.throw('Error')

但是 MyClass() 在其定义中需要一个参数,如下所示:

class MyClass{
    name:string;
    constructor(name:string){
        this.name = name;
    }
}

谢谢您的帮助。

4

1 回答 1

1

你可以使用.throw([errorLike], [errMsgMatcher], [msg])方法。

例如

index.ts

export class MyClass {
  name: string;
  constructor(name: string) {
    if (typeof name !== 'string') {
      throw new TypeError('expect "string" type for "name" argument');
    }
    this.name = name;
  }
}

index.test.ts

import { MyClass } from './';
import { expect } from 'chai';

describe('63958704', () => {
  it('should throw error if no parameter passed in the constructor', () => {
    expect(() => new MyClass(1 as any)).to.throw('expect "string" type for "name" argument');
  });
});

单元测试结果:

  63958704
    ✓ should throw error if no parameter passed in the constructor


  1 passing (43ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |      75 |       50 |     100 |      75 |                   
 index.ts |      75 |       50 |     100 |      75 | 7                 
----------|---------|----------|---------|---------|-------------------
于 2020-10-08T10:44:11.847 回答