簡體   English   中英

為什么我承諾的存根方法沒有解決?

[英]Why my promisifed stub method doesn't resolve?

我有這個身份驗證中間件:

import { promisify } from 'util';

async function verifyToken(req, res, next) {
    const [type, token] = req.headers.authorization.split(' ');

    try {
         const decoded = await promisify(jwt.verify)(token, process.env.SECRET);
         
         req.userId = decoded.id;
         
         return next();
    } catch (error) {
         return res.status(401).json({ message: 'Invalid token.' });
    }
}

這是我測試它的方式:

it('should return next and inject user id into the request', async () => { 
    req.headers.authorization = 'Bearer 1234577920fsdaf';

    sandbox.stub(jwt, 'verify').resolves({ id: 'bj435çsfkj' });

    await verifyToken(req, res, next);

    expect(req.userId).to.equal('bj435çsfkj');
    expect(next.calledOnce).to.be.true;
});

但是,在我看來,承諾並沒有解決。 當我運行測試時,出現Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves在該測試中Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves 也許它與promisify 我懷疑它確實如此,因為我已經存根了許多其他返回承諾的函數,但這是第一個引發此類錯誤的函數。

在這種情況下,如何正確存根jwt.verify

編輯:

jwt.verify來自jsonwebtoken包並具有以下簽名:

jwt.verify(token, secretOrPublicKey, [options, callback])

單元測試解決方案:

index.ts

import { promisify } from "util";
import jwt from "jsonwebtoken";

async function verifyToken(req, res, next) {
  const [type, token] = req.headers.authorization.split(" ");
  try {
    // @ts-ignore
    const decoded = await promisify(jwt.verify)(token, process.env.SECRET || "");
    // @ts-ignore
    // eslint-disable-next-line require-atomic-updates
    req.userId = decoded.id;
    return next();
  } catch (error) {
    return res.status(401).json({ message: "Invalid token." });
  }
}

export { verifyToken };

index.test.ts

import { verifyToken } from ".";
import sinon from "sinon";
import jwt from "jsonwebtoken";
import { expect } from "chai";

const sandbox = sinon.createSandbox();

describe("63795862", () => {
  afterEach(() => {
    sandbox.restore();
  });
  it("should return next and inject user id into the request", async () => {
    const req = { userId: "", headers: { authorization: "Bearer 1234577920fsdaf" } };
    const res = {};
    const next = sandbox.stub();

    const verifyStub = sandbox.stub(jwt, "verify").callsFake((token, secretOrPublicKey, callback: any) => {
      callback(null, { id: "bj435çsfkj" });
    });

    await verifyToken(req, res, next);
    sandbox.assert.calledWithExactly(verifyStub, "1234577920fsdaf", "", sinon.match.func);
    expect(req.userId).to.equal("bj435çsfkj");
    expect(next.calledOnce).to.be.true;
  });

  it("should return 401 status error", async () => {
    const req = { userId: "", headers: { authorization: "Bearer 1234577920fsdaf" } };
    const res = { status: sandbox.stub().returnsThis(), json: sandbox.stub() };
    const next = sandbox.stub();
    const mError = new Error("invalid token");
    sandbox.stub(jwt, "verify").callsFake((token, secretOrPublicKey, callback: any) => {
      callback(mError);
    });

    await verifyToken(req, res, next);

    expect(req.userId).to.equal("");
    sinon.assert.calledWithExactly(res.status, 401);
    sinon.assert.calledWithExactly(res.json, { message: "Invalid token." });
  });
});

帶有覆蓋率報告的單元測試結果:

  63795862
    ✓ should return next and inject user id into the request
    ✓ should return 401 status error


  2 passing (24ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.test.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源代碼: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/63795862

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM