首页 > 解决方案 > rejects.toThrow in Jest

问题描述

我创建了这个类:

export class ErrorList  {

  
    public HostelNotFoundError(details: ErrorDetail): FunctionalError {
        return new FunctionalError('1', 'Can\'t find this hostel', details);
    }

并在服务中:

throw new ErrorList().HostelNotFoundError({} });

我想知道在 Jest 中是否可以执行以下操作:

rejects.toThrow(HostelNotFoundError);

标签: javascriptnode.jstypescriptjestjs

解决方案


HostelNotFoundError不是类型FunctionalError,它是类的方法ErrorList它返回 的新实例FunctionalError。所以在你的单元测试中你必须使用:

rejects.toThrow(FunctionalError);

请注意,您可以使用toMatch来验证错误消息或toMatchObject验证错误的属性:

rejects.toMatch('Can\'t find this hostel');

推荐阅读