簡體   English   中英

控制器設置會話數據時 Supertest 單元測試超時

[英]Supertest unit test timing out when controller sets session data

我正在嘗試對我的應用程序運行單元測試,但單元測試超時。 當我深入研究它時,我發現它在應用程序試圖設置會話數據的地方超時。 如果我刪除會話設置代碼行,單元測試將繼續(但由於需要會話數據而失敗)。

// unit test code;
describe('Check if endpoint are reachable', () => {

  before(function(done) {
    // call /router to generate session;
    AGENT.get('/router')
        .query(clientData)
        .expect(302)
        .end((err, res) => {
            if (!err) {
                done()
            } else {
                done(err);
            }
        });
  });

  //  .......

});


// controller code where the session is set;

// .....

req.session.clientData = clientData;

// ....

當我運行代碼時,出現以下錯誤:錯誤:超過 2000 毫秒超時。 對於異步測試和鈎子,確保調用“done()”; 如果返回 Promise,請確保它已解決。 (C:\\Nedbank\\aa-serverui\\application\\tests\\authorise.js)

但是,如果我注釋掉會話設置行 ( // req.session.clientData = clientData; ),那么測試將繼續按預期運行。

這是一個最小的工作示例:

app.js

const express = require("express");
const session = require("express-session");
const app = express();

app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true },
  }),
);

function controller(req, res) {
  const clientData = req.query;
  console.log(clientData);
  req.session.clientData = clientData;
  res.sendStatus(302);
}

app.get("/router", controller);

app.get("/api", (req, res) => {
  res.sendStatus(200);
});

module.exports = app;

app.test.js :

const supertest = require("supertest");
const app = require("./app");
const agent = supertest(app);
const { expect } = require("chai");

describe("Check if endpoint are reachable", () => {
  const clientData = { name: "supertest" };
  before((done) => {
    agent
      .get("/router")
      .query(clientData)
      .expect(302)
      .end((err, res) => {
        if (!err) {
          done();
        } else {
          done(err);
        }
      });
  });

  it("should pass", async () => {
    const res = await agent.get("/api");
    expect(res.status).to.be.eq(200);
  });
});

帶有覆蓋率報告的集成測試結果:

  Check if endpoint are reachable
{ name: 'supertest' }
    ✓ should pass


  1 passing (44ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |    96.15 |       50 |      100 |    96.15 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |    92.86 |       50 |      100 |    92.86 |                17 |
-------------|----------|----------|----------|----------|-------------------|

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

暫無
暫無

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

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