使用sinon jest supertest进行超时异步回调测试以在Express API上模拟错误500

时间:2020-07-27 20:01:04

标签: express testing jestjs sinon stub

我正在测试具有所有http 500错误的api。

在这里,我尝试使用sinon.stub在发生故障的服务器上进行测试并收到500错误,但是我收到了timeOut异步回调,或者如果我使用我的应用成功显示了200响应statusCode,就好像sinon.stub没有任何作用。我必须错过一些东西,我被困住了...

您会在下面看到一个可怕的错误吗?

感谢您的宝贵帮助

process.env.NODE_ENV = "test";
const app = require("../../app");
const request = require("supertest");
const sinon = require("sinon");
// /************************** */
const usersRoute = require("../../routes/Users");
const express = require("express");

const initUsers = () => {
  const app = express();
  app.use(usersRoute);
  return app;
};

describe("all 5xx errors tested with stub", function () {
  it("should return a 500 when an error is encountered", async (done) => {
    let secondApp;

    sinon.stub(usersRoute, "post").throws(
      new Error({
        response: { status: 500, data: { message: "failed" } },
      })
    );
    secondApp = initUsers(); //==========> Timeout Async Callback
    //secondApp = require("../../app"); //==============> gives a 200 instead of 500
    const fiveHundredError = await request(secondApp)
      .post("/users/oauth?grant_type=client_credentials")
      .send({
        username: "digitalAccount",
        password: "clientSecret",
      });

    expect(fiveHundredError.statusCode).toBe(500); 
    //sinon.restore();
    done();
  });
});

应用程序正在使用express.Router获取用户路由:

const express = require("express");
const router = express.Router();
const axios = require("axios");

router.post("/users/oauth", async (req, res) => {
  //if (all missing parts)
  //else {
    try {

      if (req.fields) {
        const response = await axios.post(
          `${base_url}oauth/token?grant_type=${req.query.grant_type}`,
          {},
          {
            auth: {
              username: req.fields.username,
              password: req.fields.password,
            },
          }
        );
        res.json(response.data);
      }
    } catch (error) {
      return res.status(error.response.status).json(error.response.data);
    }
  }
});

module.exports = router;

请参阅server.js:

const app = require("./app");

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`server starting on port ${port}!`));

和app.js:

// private environment:
require("dotenv").config();
const express = require("express");
const formidableMiddleware = require("express-formidable");
const cors = require("cors");


const app = express();

app.use(formidableMiddleware());
app.use(cors());

const usersRoute = require("./routes/Users");
app.use(usersRoute);

app.get("/", (req, res) => {
  res.status(200).send("Welcome to Spark Admin back end!");
});

app.all("*", (req, res) => {
  return res.status(404).json({ error: "Web url not found" });
});

module.exports = app;

1 个答案:

答案 0 :(得分:0)

我最终选择了'nock'并删除了'sinon'

var array = [{ a:'ai', b:'bi', c:['first','second','third']}]
   
var res = array.map((o)=>{return Object.values(o)[2].map(e => {
var newob = {...o}
newob.cSplit = e
  return newob
  })   
})
    console.log(res)