我正在使用摩卡,柴,西农进行单元测试。 我想对错误处理程序功能进行单元测试:
import { logger } from '../service/logger';
import { InternalServerError } from './InternalServerError';
export function errorHandler(error: any, req: any, res: any, next: any) {
logger.error(error.message);
return res.status(500).json(new InternalServerError(error.message));
}
这是测试功能
import { expect, sinon } from '../../helpers/chai';
import { InternalServerError } from '../../../errors/InternalServerError';
import { errorHandler } from '../../../errors/ErrorHandler';
import 'mocha';
describe('ErrorHandler', () => {
it('Handles Error', () => {
const logger = {
error: sinon.spy()
};
const res = { status: sinon.stub(), json: sinon.spy() };
res.status.withArgs(500).returns(res);
const req = {};
const error = new InternalServerError();
const next = sinon.spy();
errorHandler(error, req, res, next);
return Promise.all([
expect(logger.error.withArgs(error)).to.be.calledOnce,
expect(
res.json.withArgs({
message: 'Internal server error'
})
).to.be.calledOnce
]);
});
});
这是帮助文件
import * as sinon from 'sinon';
import { expect } from 'chai';
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
import * as chaiAsPromised from 'chai-as-promised';
chai.use(sinonChai);
chai.use(chaiAsPromised);
chai.config.includeStack = true;
export { expect, sinon };
我得到了这个结果: 0通过(35ms) 1个失败
1)ErrorHandler 处理错误: TypeError:[Function:errorHandler]不是间谍,也不是间谍!
我如何通过此单元测试。