should.js做测试驱动,对抛出异常的测试用例无法识别
发布于 9 年前 作者 qianjiahao 4308 次浏览 最后一次编辑是 8 年前 来自 问答

在学习测试驱动开发编写测试用例,但是由于should.js的库的改变,以前的写法已经无法通过了,后来查看了should.js的官网api,意思好像是这里应该用assert.js来些测试用例。

源代码里

if(n > 10){
	throw new Error('n should <= 10');
}

测试代码里

it('should throw when n > 10', function () {
	(function () {
		main.fibonacci(11);
	}).should.throws('n should <= 10');
    //should.js  3.x  现在用不了了

});

后来在assert.js的官网上看到这样的写法

assert.throws(
  function() {
    throw new Error("Wrong value");
  },
  Error
);

于是就改成这样

it('should throw when n > 10', function () {
	
	assert.throws(
      function () {
		throw new Error('n should <= 10');
	  },
      main.fibonacci(11)
    );
});

但是依然无效,应该怎么写这个测试用例呢?

3 回复

should@6.0.1

var should = require('should');
describe('test', function() {
	it('throw', function() {
		function isPositive(n) { 
			if(n <= 0) throw new Error('Given number is not positive')
		}
		isPositive.bind(null, 10).should.not.throw();
		isPositive.bind(null, -10).should.throw();
	});
});

楼上正解,原因是js捕获异常时无法捕获该方法中调用的其他方法的异常,只对该方法范围内的才能捕获。

var should = require('should');
describe('test', function() {
	it('throw', function() {
		//js捕获异常时无法捕获该方法中调用的其他方法的异常,只对该方法范围内的才能捕获。
		//使用bind函数改变this
		return main.fibonacci.bind(null, 11).should.throw('n should <= 10');
	});
});
回到顶部