找不到超级测试错误测试表达端点 [英] supertest not found error testing express endpoint

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

问题描述

我尝试设置玩笑,超级测试和表达,但失败了.我有这两个简单的文件

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(),但我们不希望调用"listen".

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);
      });
  });
});

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

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