【问题标题】:Test express router with mocha用 mocha 测试 express 路由器
【发布时间】:2020-03-23 11:37:26
【问题描述】:

我遇到了一个关于 express (node.js) 中路由的奇怪行为。

我正在尝试测试一个 api。

服务器挂载:

app.use("/", productRouter);
app.use("/", testRouter);

productRouter.post("/products", ...);
testRouter.post("/test", ...);

如果我 POST 到:

http://localhost:MYPORT/test
http://localhost:MYPORT/products

一切正常。

但是如果我运行这个 mocha 测试:

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

describe(" ====== Test for argumentMiddleware: a factory to check request arguments ======", () => {
  describe("requiredArgument middleware", () => {
    it("it should return error if requiredArgument is not in the body of request:", done => {
      let requestBody = {
        argument: "product"
      };
      chai
        .request(app)
        .post("/test")
        .send(requestBody)
        .end((err: Error, res: any) => {
          res.should.have.status(400);
          console.log(err.message);
          done();
        });
    });
    it.skip("it should pass if requiredArgument is in the body of request: ", done => {
      let requestBody = {
        requiredArgument: "product"
      };
      chai
        .request(app)
        .post("/test")
        .send(requestBody)
        .end((err: Error, res: any) => {
          res.should.have.status(200);
          done();
        });
    });
  });
});

我确定它对/products 而不是/test 执行POST,我在/products 中有一个console.log,它会被执行。为什么它被路由到那个端点,它发生只是因为它首先被声明了?

【问题讨论】:

    标签: javascript express mocha.js router


    【解决方案1】:

    这部分看起来很奇怪:

    app.use("/", productRouter);
    app.use("/", testRouter);
    

    如果您更改了 testRouter 的 ("/") 部分并可能变成这样会发生什么:

    app.use(testRouter);

    app.use("/api", testRouter);

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 2017-01-25
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多