未找到 supertest 错误测试快速端点 [英] supertest not found error testing express endpoint

查看:24
本文介绍了未找到 supertest 错误测试快速端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试设置 jest、supertest 和 express,但失败了.我有这两个简单的文件

I tried to setup jest, supertest and express but failed. I have these 2 simple file

index.js

const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => res.send("Hello World!"));

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

和 index.test.js

and index.test.js

const express = require("express");
const app = express();
const request = require("supertest");

describe("/", () => {
  test("it says hello world", done => {
    request(app)
      .get("/")
      .expect(200)
      .end(function(err, res) {
        console.log("err", err);
      });
  });
});

当我运行测试时出现此错误.err 错误:预期 200 OK",得到 404 Not Found"

when I run the test I'm getting this error. err Error: expected 200 "OK", got 404 "Not Found"

怎么了?

我在浏览器中访问 localhost:3000 我可以看到Hello World!"

I visit to localhost:3000 in my browser I can see 'Hello World!'

推荐答案

你应该重构 index.js 并创建 app.js

you should refactor index.js and create app.js

app.js

const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Hello World!"));

index.js

const app = require('./app')
const port = process.env.PORT
app.listen(port, () => { console.log(`listening on ${port}) . })

我们像这样重构代码的原因是我们需要访问 express app() 但我们不希望听"被调用.

the reason why we restructure the code like this is we need to access to express app() but we do not want "listen" to be called.

in your test file

const request = require("supertest");
const app = require("../src/app");

describe("/", () => {
  test("it says hello world", done => {
    request(app)
      .get("/")
      .expect(200)
      .end(function(err, res) {
        console.log("err", err);
      });
  });
});

这篇关于未找到 supertest 错误测试快速端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆