【发布时间】:2019-03-04 01:50:55
【问题描述】:
我有以下 js 用于对错误处理程序进行单元测试:
import assert from 'assert';
import deepClone from 'lodash.clonedeep';
import deepEqual from 'lodash.isequal';
import { spy } from 'sinon';
import errorHandler from './index';
function getValidError(constructor = SyntaxError) {
let error = new constructor();
error.status = 400;
error.body = {};
error.type = 'entity.parse.failed';
return error;
}
describe('errorHandler', function() {
let err;
let req;
let res;
let next;
let clonedRes;
describe('When the error is not an instance of SyntaxError', function() {
err = getValidError(Error);
req = {};
res = {};
next = spy();
clonedRes = deepClone(res);
errorHandler(err, req, res, next);
it('should not modify res', function() {
assert(deepEqual(res, clonedRes));
});
it('should call next()', function() {
assert(next.calledOnce);
});
});
...(#other test cases all similar to the first)
describe('When the error is a SyntaxError, with a 400 status, has a `body` property set, and has type `entity.parse.failed`', function() {
err = getValidError();
req = {};
let res = {
status: spy(),
set: spy(),
json: spy()
};
let next = spy();
errorHandler(err, req, res, next);
it('should set res with a 400 status code', function() {
assert(res.status.calledOnce);
assert(res.status.calledWithExactly(400));
});
it('should set res with an application/json content-type header', function() {
assert(res.set.calledOnce);
assert(res.set.calledWithExactly('Content-Type', 'application/json'));
});
it('should set res.json with error code', function() {
assert(res.json.calledOnce);
assert(res.json.calledWithExactly({ message: 'Payload should be in JSON format' }));
});
});
});
请注意,在“当错误是 SyntaxError...”的描述块中,res、next 和 clonedRes 前面有 let。
如果没有let 在这些前面,我的测试会失败。我不明白为什么我需要再次为这些添加let,而不是在同一块中添加err 和req。谁能帮我解释一下?
【问题讨论】:
-
显式声明变量总是一个好习惯(使用
var或let)。 Javascript 应该理解隐式声明的变量,但它可能会遇到问题,就像你的情况一样。
标签: javascript unit-testing let