sup*_*tle 4 unit-testing super ecmascript-6 jestjs
我有一个自定义错误类,该类扩展了Javascript中的内置Error类。我想到的问题是,是否通过我的Jest单元测试调用了“ super()”方法。
export class AppError extends Error {
public name: string;
public message: string;
public status?: number;
public data?: any;
constructor(message: string, status?: number, data?: any) {
super(); <-- this guy!!
this.name = 'AppError';
this.status = status || 500;
this.message = message;
this.data = data;
}
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以测试吗?谢谢。
没有理由检查super()在本机ES6类或通过Babel转译的类中是否都未调用。
不调用super子类构造函数将导致类实例化错误:
ReferenceError:必须在派生类中调用超级构造函数,然后才能访问“ this”或从派生构造函数返回
Babel也为此提供了保护措施:
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
Run Code Online (Sandbox Code Playgroud)
可以super()通过模拟子类原型来检查是否调用了父构造函数(对声明参数很有用),例如:
let ParentOriginal;
let ParentMock;
beforeEach(() => {
ParentOriginal = Object.getPrototypeOf(AppError);
ParentMock = jest.fn();
Object.setPrototypeOf(AppError, ParentMock);
});
it('..', () => {
new AppError(...);
expect(ParentMock.mock.calls.length).toBe(1);
})
afterEach(() => {
Object.setPrototypeOf(AppError, ParentOriginal);
});
Run Code Online (Sandbox Code Playgroud)
可以super在本机类和使用Babel转译的类中进行模拟。
但是此测试是多余的,因为丢失super()将以任何方式导致错误。测试是AppError从继承Error的一切需要在这里进行测试:
expect(new AppError(...)).toBeInstanceOf(Error)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2171 次 |
| 最近记录: |