简体   繁体   English

如何在JavaScript中使用Mocha和assert.throws测试参数的值?

[英]How to test the value of an argument using Mocha and assert.throws in JavaScript?

I want to see if a value that equals 'x' will cause my function to throw an exception. 我想看看是否等于“ x”的值会导致我的函数引发异常。 I have a unit test that checks if a block will throw an exception, but I want the exception to be thrown only if the argument = 'x', not if its just empty. 我有一个单元测试,它检查一个块是否会引发异常,但是我希望仅当参数='x'时才引发异常,而不是仅当它为空时才引发异常。 How do I do this using assert? 如何使用assert做到这一点?

Here's some code to illustrate what I mean: 这是一些代码来说明我的意思:

// Some function to check if a color is not transparent.
function checkColor(color) {
  if (color == 'transparent') {
    throw new TypeError('cant have transparent colors!');
  } else {
    return color;
  }
}

Here's the assert: 这是断言:

assert.throws(checkColor, /cant have transparent colors!/);

Now, I know that assertion will fail because my function only throws the exception if the color == 'transparent'. 现在,我知道断言将失败,因为如果color =='transparent',我的函数只会引发异常。 Using Mocha and Assert, how do I test the assertion as I want it? 使用Mocha和Assert,如何根据需要测试断言? I don't want to merely test if color !== undefined or is of some type. 我不想只是测试颜色!==未定义还是某种类型。 I specifically want to see if the exception is raised under the specific circumstance above - which is the only circumstance I want the exception to be raised (since having an empty color, is actually handled elsewhere). 我特别想查看在上述特定情况下是否引发了异常-这是我希望引发异常的唯一情况(由于颜色为空,实际上是在其他地方处理的)。

assert.throw(function() { iThrowError(argument) }, Error)

现在只要确定参数= x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM