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

问题描述 投票:1回答:1

我有一个简单的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
javascript node.js mocha sinon chai
1个回答
1
投票

从查看您发布的代码,您的函数返回另一个需要调用的函数。所以测试应该用这种方式编写:

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的值。

© www.soinside.com 2019 - 2024. All rights reserved.