首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >should.throw()、should.Throw()和expect to.throw()有什么区别?

should.throw()、should.Throw()和expect to.throw()有什么区别?
EN

Stack Overflow用户
提问于 2018-06-08 10:16:49
回答 1查看 459关注 0票数 0

我读到了chai.should()和chai.expect()应该以相同的方式工作的the document,但当我尝试捕获错误时,它似乎不同。根据我的理解,我可以使用chain ()将promise chain断言为

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
myfunction.should.be.rejectedWith(Error)

但是,由于该函数将在promise链之前抛出错误,因此错误不会进入promise链内部,因此我不能使用此方法。然后我使用下面的方法。

如你所见,

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
() => myFunctionA(name).should.throw('argument name is undefine'); 

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
expect(() => myFunctionA(name).to.throw('Argument "stackName" is undefined');

根据文档,它们应该具有相同的效果,或者以相同的方式工作,但是,前者总是会通过,即使我从我的源代码中删除了错误抛出。不管怎样,它都会过去的。只有后者才能正常工作。有人知道为什么吗?你有更好的主意来测试“抛出错误”吗?

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
function myFunctionA(name) {
    if (!name) {
        throw new Error('argument name is undefine')
    }
    return Promise.resolve();
}


it.only('should throw Error if name is null|undefined ', () => {
    let name;
    () => myFunctionA(name).should.throw('argument name is undefine'); //this would pass no matter how
    () => myFunctionA(name).should.Throw('argument name is undefine'); //this would pass no matter how
    expect(() => myFunctionA(name).to.throw('Argument "stackName" is undefined'); // this will do the assert properly, this is work
    return myFunctionA(name).should.throw(Error);// this will failed to catch the Error
});

EN

回答 1

Stack Overflow用户

发布于 2018-06-08 15:33:49

因此,在前两种情况下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    () => myFunctionA(name).should.throw('argument name is undefine'); //this would pass no matter how
    () => myFunctionA(name).should.Throw('argument name is undefine'); //this would pass no matter how

您正在创建一个从未调用过的匿名函数() => myFunctionA(name),因此您实际上并没有调用myFunctionA

对于最后一种情况

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
myFunctionA(name).should.throw(Error);// this will failed to catch the Error

这是不起作用的,因为您的代码在.should可以运行之前抛出错误。从这里的文档中,您应该像在3个案例中一样使用它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50758412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文