为错误案例写茉莉测试柜,以使其变为绿色
我有一个函数返回最多的参数列表,如果有5个以上的参数,它将引发错误:
if (params.length > 5) {
throw new Error('Too many arguments');
}
当我们在茉莉花中为单位测试编写testCase时,我们如何期望情况下的值在此类错误中(即测试柜将成功 - 绿色),因为它不是函数的返回值? 这是我的测试代码:
const myLocalVariable1 = require('../src/get-bigest-number');
describe('CommonJS modules', () => {
it('should import whole module using module.exports = getBiggestNumber;', async () => {
const result = myLocalVariable1.getBiggestNumber(1, 3, 6, 5, 4, 7);
expect(result).toBe(new Error('Too many arguments'));
});
});
I have a function that returns the largest number of a variant list of parameters, and if there are more than 5 parameters it will throw an error:
if (params.length > 5) {
throw new Error('Too many arguments');
}
When we write testcase for unit-test in Jasmine, how do we expect the value for the case of such errors (so that the testcase would be successful - green color), because it is not the returned value of the function?
Here is my code in testing:
const myLocalVariable1 = require('../src/get-bigest-number');
describe('CommonJS modules', () => {
it('should import whole module using module.exports = getBiggestNumber;', async () => {
const result = myLocalVariable1.getBiggestNumber(1, 3, 6, 5, 4, 7);
expect(result).toBe(new Error('Too many arguments'));
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为应该这样(不要将其分配给结果,然后断言结果):
您也可以使用try/catch的库存JavaScript方法:
I think it should be like this (Don't assign it to result and then assert result):
You can also do it the stock JavaScript way with try/catch:
有一个茉莉匹配器
可用于检查错误是否丢弃。您可以选择将自定义错误和/或错误消息作为参数传递,以检查是否获得了期望的错误,而不是其他错误。
在您的情况下,请
注意,您必须将功能调用放置在另一个功能中,否则函数的执行会触发错误并打破测试。
但是,如果您的函数没有任何参数,则可以将功能传递给
期望
:There is a Jasmine matcher
toThrowError
that can be used to check that an error is thrown. You can optionally pass a custom error and/or an error message as argument to check that you get the error you expect and not some other error.In your case, it would be:
Note that you have to place your function call inside another function, otherwise the execution of your function triggers the error and breaks the test.
However, if your function does not take any arguments, you can simply pass the function to the
expect
: