如何使用 mocha、chai 和 sinon 模拟和测试闭包

How to mock, and test, closures with mocha, chai and sinon

我有一个简单的 Node.js 中间件,我想测试它是否被正确处理。

简单的中间件

module.exports = (argumentOne, argumentTwo) => (req, res, next) => {
  if (!argumentOne || !argumentTwo) {
    throw new Error('I am not working');
  };

  req.requestBoundArgumentOne = argumentOne;
  req.requestBoundArgumentTwo = argumentTwo;

  next();
};

我想使用 mocha、chai 和 sinon 测试这个中间件,但我就是不知道如何测试这个内部函数。

我试过以下方法

describe('[MIDDLEWARE] TEST POSITIVE', () => {
  it('should work', () => {
    expect(middleware('VALID', 'TESTING MIDDLEWARE')).to.not.throw();
  });
});

describe('[MIDDLEWARE] TEST NEGATIVE', () => {
  it('shouldn\'t work', () => {
    expect(middleware('INVALID')).to.throw();
  });
});

在我的 TEST POSITIVE 中,我知道这段代码是有效的,但它仍然抛出以下错误

AssertionError: expected [Function] to not throw an error but 'TypeError: Cannot set property \'requestBoundArgumentOne\' of undefined' was thrown

从查看您发布的代码来看,您的函数 returns 是另一个需要调用的函数。所以测试应该这样写:

describe('middleware', () => {
  let req, res, next;

  beforeEach(() => {
    // mock and stub req, res
    next = sinon.stub();
  });

  it('should throw an error when argumentOne is undefined', () => {
    const fn = middleware(undefined, 'something');
    expect(fn(req, res, next)).to.throw();
  });

  it('should throw an error when argumentTwo is undefined', () => {
    const fn = middleware('something', undefined);
    expect(fn(req, res, next)).to.throw();
  });

  it('should call next', () => {
    const fn = middleware('something', 'something');
    fn(req, res, next);
    expect(next.calledOnce).to.be.true;
  });
});

要正确测试成功案例,您需要删除 reqres 的值。