Mocha/Chai 测试中间件头

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

我一直在尝试学习 Mocha/Chai 单元测试库,并且一直在学习 Udemy 上 Maximillian 的 NodeJS 课程。

根据本课程陷入测试中间件的困境。

我的问题是使用 Mocha/Chai 进行单元测试中间件错误的正确方法是什么?

您可以在下面看到我的代码。

身份验证中间件:

const jwt = require("jsonwebtoken");

const HttpError = require("../models/http-error");

module.exports = (req, res, next) => {
  if(req.method === 'OPTIONS'){
    return next();
  }
  try {

    const authHeader = req.get('Authorization');
    if(!authHeader){
      return next(new HttpError('Not authenticated', 401));
    }

    const token = req.headers.authorization.split(" ")[1]; // Authorization: 'Bearer TOKEN'
    if (!token) {
      return next(new HttpError("Authentication failed!", 401));
    }

    const decodedToken = jwt.verify(token, "supersecret_dont_share");
    req.userData = { userId: decodedToken.userId };
    next();
  } catch (err) {
    return next(new HttpError("Authentication failed!", 401));
  }
};

HTTP错误:

class HttpError extends Error{
    constructor(message, errorCode){
        super(message);
        this.code = errorCode;
    }
}

module.exports = HttpError;

authMiddleware.test.js:

const expect = require('chai').expect;
const HttpError = require("../models/http-error");

const authMiddleware = require('../middleware/check-auth');

it('It should throw an error if no auth header is present', function(){
    const req = {
        get: function () {
            return null;
        }
    }

    const httpError = new HttpError('Not authenticated', 401);

    expect(authMiddleware.bind(this, req, {}, ()=>{})).to.have.property('message');
});

尝试过:

expect(authMiddleware.bind(this, req, {}, ()=>{})).to.throw();
expect(authMiddleware.bind(this, req, {}, ()=>{})).to.throw(Error);
expect(authMiddleware.bind(this, req, {}, ()=>{})).to.throw(HttpError);
expect(authMiddleware.bind(this, req, {}, ()=>{})).to.be.instanceOf(HttpError);
expect(authMiddleware.bind(this, req, {}, ()=>{})).to.be.instanceOf(Error);
expect(authMiddleware.bind(this, req, {}, ()=>{})).to.have.property('message');

以上均未通过测试。

如有任何建议,我们将不胜感激。

node.js express unit-testing mocha.js chai
1个回答
0
投票

我遇到了和你完全相同的问题,我是这样解决的:

const chai = require("chai");
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
const { expect } = chai;

const sinon = require("sinon");
const jwt = require("jsonwebtoken");

const authMiddleware = require("../middleware/check-auth");
const HttpError = require("../models/http-error");

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

  beforeEach(() => {
    req = {
      headers: {},
      cookies: {},
    };
    res = {
      removeHeader: sinon.spy(),
    };
    next = sinon.spy();
  });

  afterEach(() => {
    sinon.restore();
  });

  it("should throw an error if no authorization header or cookie is present", async () => {
    await authMiddleware(req, res, next);

    expect(next.calledOnce).to.be.true;
    expect(next.calledWith(sinon.match.instanceOf(HttpError))).to.be.true;
  });
});

记得添加:

 npm install --save-dev chai-as-promised
© www.soinside.com 2019 - 2024. All rights reserved.