标签: supertest

在npm下摩卡观看失败

我有一个非常简单的Koa应用程序:

var app = module.exports = require("koa")();

app.use(function *(){
    this.body = "Koa says Hi!";
});

var port = process.env.PORT || (process.argv[2] || 3000);
port = (typeof port === "number") ? port : 3000;

app.listen(port);
console.log("Application started. Listening on port:" + port);
Run Code Online (Sandbox Code Playgroud)

我用这样的mocha和supertest测试;

var app = require("../");
var request = require("supertest").agent(app.listen());

describe("Our amazing site", function () {

    it("has a nice welcoming message", function (done) {
        request
            .get("/")
            .expect("Koa says Hi!")
            .end(done);
    });
});
Run Code Online (Sandbox Code Playgroud)

我想看看我的文件的变化,并使用这样的-w标志

mocha -u bdd -R min …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js npm supertest koa

13
推荐指数
1
解决办法
4727
查看次数

使用 Supertest 时 request.cookies 未定义

我通过 NestJS API 中的 HTTP-Only cookie 传递身份验证令牌。

因此,在为我的 Auth 端点编写一些 E2E 测试时,我遇到了 cookie 不在我期望的位置的问题。

这是我精简的测试代码:

describe('auth/logout', () => {
  it('should log out a user', async (done) => {
    // ... code to create user account

    const loginResponse: Response = await request(app.getHttpServer())
                                              .post('/auth/login')
                                              .send({ username: newUser.email, password });

    // get cookie manually from response.headers['set-cookie']
    const cookie = getCookieFromHeaders(loginResponse);

    // Log out the new user
    const logoutResponse: Response = await request(app.getHttpServer())
                                            .get('/auth/logout')
                                            .set('Cookie', [cookie]);

  });
});
Run Code Online (Sandbox Code Playgroud)

在我的 JWT 策略中,我使用自定义 cookie 解析器。我遇到的问题是request.cookies …

cookies supertest nestjs

13
推荐指数
2
解决办法
1万
查看次数

异步外部函数留下开放句柄 - Jest、Supertest、Express

我开始使用 Jest 和 Supertest(针对端点)测试我的应用程序。测试工作顺利,但Jest 在运行测试后检测到 2 个打开的句柄,这会阻止 Jest 干净退出。

\n

这个打开的句柄是由我的测试文件中调用的外部异步函数生成的。我正在使用外部函数从 Auth0 API 请求 JWT 令牌;但对 Auth0 的请求还在其响应中提供了传递端点中间件的关键信息(有关此的更多信息如下)。这里要记住两件事:

\n
    \n
  1. 到目前为止,我无法避免从 Auth0 请求令牌,因为正如我所说,该响应还包含一个user具有关键信息的对象。Auth0 将此对象设置在主体响应之外的同一级别,但不在其中。该信息是传递端点中间件的关键。
  2. \n
  3. 我已经隔离了所有错误,以确保仅当我调用从 Auth0 API 请求令牌和用户信息的外部异步函数时才会出现问题;该问题是通过使用getToken测试文件中的该函数(称为 )生成的。
  4. \n
\n

测试文件代码

\n
import app from "../app";\nimport mongoose from "mongoose";\nimport supertest from "supertest";\nimport { getToken } from "../helpers";\nimport dotenv from "dotenv";\nimport * as config from "../config";\n\ndotenv.config();\n\nconst api = supertest(app);\n\nlet authToken: any;\nlet db: any;\n\nbeforeAll(async() => {\n  try {\n    mongoose.connect(config.MONGODB_URI, {\n      useNewUrlParser: true,\n      useUnifiedTopology: true,\n      useCreateIndex: …
Run Code Online (Sandbox Code Playgroud)

node.js express supertest jestjs

13
推荐指数
1
解决办法
2722
查看次数

Node.js/Express/Mocha/Supertest Rest API - 空请求正文

我到处寻找可以找到解决方案.我发现的唯一一件事是没有回复的帖子.如果我忽略了某些事情,我会道歉.

问题是,当我尝试获取API中的POST值时/createQuestion,正文是空的/未定义的.我Cannot read proprety 'question' of undefined从API 那里得到这样的错误.

Express API:

app.post("/createQuestion", function(req, res) {
    var questionType = req.body.question.type;
    var questionText = req.body.question.text;
    var questionDuringClass = req.body.question.duringClass;

    // Do a bunch of stuff

    res.send(response);
});
Run Code Online (Sandbox Code Playgroud)

考试:

    var should = require('should'); 
    var assert = require('assert');
    var request = require('supertest');  
    var winston = require('winston');

    request = request('http://localhost:8080');

        describe('Questions', function() { // Test suite
            before(function(done) {
                done();
            });

        it('Should create a freeResponse question', function(done) { // Test case …
Run Code Online (Sandbox Code Playgroud)

rest mocha.js node.js express supertest

12
推荐指数
1
解决办法
2万
查看次数

使用mocha和超级测试进行NodeJS HTTPS API测试 - "DEPTH_ZERO_SELF_SIGNED_CERT"

我需要测试通过提供一个API HTTPSmochasuper test (证书都没有过期)

这是服务器的要点:

...
var app = express();
var _options = {
    key: fs.readFileSync('my-key.pem');,
    cert: fs.readFileSync('my-cert.pem')
};

// Start HTTPS server
https.createServer(_options, app).listen(app.get('port'), app.get('ip'), function () {

 // ok or not logs

});
Run Code Online (Sandbox Code Playgroud)

这是要测试的路线

app.get('/hello',function (req, res) {
   res.json(200);
});
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用此代码进行测试 test/test.js

    var supertest = require('supertest'),
        api = supertest('https://localhost:3000');

describe('Hello test', function () {

      it('hello', function (done) {

        api.get('/hello')
               .expect(200)
               .end(function (err, res) {
                                        if (err) {
                                                   done(err);
                                        } else {
                                                   done();
               }
         }); …
Run Code Online (Sandbox Code Playgroud)

javascript https mocha.js node.js supertest

12
推荐指数
1
解决办法
3534
查看次数

在Mocha和SuperTest中设置基本身份验证

我正在尝试为我们设置测试,以验证用户名和密码的基本身份验证阻止的路径的用户名和密码.

it('should receive a status code of 200 with login', function(done) {
    request(url)
        .get("/staging")
        .expect(200)
        .set('Authorization', 'Basic username:password')
        .end(function(err, res) {
            if (err) {
                throw err;
            }

            done();
        });
});
Run Code Online (Sandbox Code Playgroud)

javascript mocha.js basic-authentication node.js supertest

12
推荐指数
1
解决办法
9702
查看次数

在mocha中运行supertest时如何获得实际的服务器错误?

我有使用supertest和mocha的代码:

import request from 'supertest';

//....

var newGame;
describe('Creating game', function() {
  beforeEach(function(done) {
    request(app)
      .post('/api/games')
      .send({
        owner: 'Mr. X',
      })
      .expect(201)
      .expect('Content-Type', /json/)
      .end((err, res) => {
        if (err) {
          return done(err);
        }
        newGame = res.body;
        done();
      });
  });    

  describe('the created game', function() {

    it('should name the specified owner', function() {
      newGame.owner.should.equal('Mr. X');
    });

   ...
  })
});
Run Code Online (Sandbox Code Playgroud)

当服务器代码抛出一些异常(例如访问未定义对象的属性)时,我得到了这个堆栈跟踪

Error: expected 201 "Created", got 500 "Internal Server Error"
  at Test._assertStatus (D:\Codes\theApp\node_modules\supertest\lib\test.js:232:12)
  at Test._assertFunction (D:\Codes\theApp\node_modules\supertest\lib\test.js:247:11)
  at Test.assert (D:\Codes\theApp\node_modules\supertest\lib\test.js:148:18)
  at Server.assert (D:\Codes\theApp\node_modules\supertest\lib\test.js:127:12) …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js supertest

12
推荐指数
1
解决办法
3543
查看次数

TypeError:无法读取未定义的supertest的属性"address"

我需要一些帮助来解决我在nodejs代码上测试的问题.我正在使用摩卡和超级.我对supertest中的实现感到困惑.我不知道解决了.我正在尝试自动下载文件.

`describe('GET /entry/:entryId/file/:id/download', function(){
 it('should pass download function', function(done){
   this.timeout(15000);
   request(app.webServer)
  .get('/entry/543CGsdadtrE/file/wDRDasdDASAS/download')
  .set('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGco')
  .expect(200)
  .end(function(err, res){
  if (err) return done(err);
  console.log(err, res);
  done();
 });
});
});
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js supertest

12
推荐指数
2
解决办法
1万
查看次数

成组运行 Jest 测试套件

我正在通过 Jest 和 supertest 为新 API 编写大量测试。在运行测试之前,我正在设置一个测试数据库并用用户填充它:

测试命令

jest --forceExit --config src/utils/testing/jest.config.js
Run Code Online (Sandbox Code Playgroud)

文件jest.config.js

module.exports = {
  rootDir: process.cwd(),

  // Sets up testing database with users
  globalSetup: './src/utils/testing/jest.setup.js',

  // Ensures connection to database for all test suites
  setupTestFrameworkScriptFile: './src/utils/testing/jest.db.js',

}
Run Code Online (Sandbox Code Playgroud)

所以我从一些用户的数据库开始进行测试。问题是这样的:

我的一些测试依赖于其他测试的成功。在这个应用程序中,用户可以上传图像,并将它们分组。所以我的分组端点套件取决于我的图像上传套件的成功,等等。

我很清楚很多人可能会说这是不好的做法,并且测试不应该依赖于其他测试。话虽如此,我真的宁愿通过以下方式保留所有测试supertest,而不是进入依赖注入等。我不想精心设置测试条件(例如,在运行之前人为地创建一堆用户图像)测试),因为:(1)这只是逻辑的重复,并且(2)它增加了某些破坏的可能性。

有什么办法可以将 Jest Suite 分组吗?例如,要按顺序运行套件:

jest run creationSuite
jest run modificationSuite
Run Code Online (Sandbox Code Playgroud)

这样,我所有的“creationSuite”测试都可以同时运行,并且所有测试的成功都会触发“modificationSuite”以快速失败的方式运行等。

或者,在测试套件内部指定对其他测试套件的依赖会很棒:

describe('Grouping endpoint', () => {
    // Somehow define dependencies
    this.dependsOn(uploadSuite)
Run Code Online (Sandbox Code Playgroud)

javascript testing supertest ecmascript-6 jestjs

12
推荐指数
3
解决办法
1万
查看次数

res.body在这个使用supertest和Node.js的测试中是空的

我正在使用supertest测试Node.js API ,我无法解释为什么res.body对象超集返回为空.数据显示在res.text对象中,但不是res.body,任何想法如何解决这个问题?

我正在使用Express和body-parser:

app.use(bodyParser.json());
app.use(bodyParser.json({ type: jsonMimeType }));
app.use(bodyParser.urlencoded({ extended: true }));
Run Code Online (Sandbox Code Playgroud)

这是我正在测试的API方法:

app.get(apiPath + '/menu', function(req, res) {
  var expiration = getExpiration();

  res.set({
    'Content-Type': jsonMimeType,
    'Content-Length': jsonTestData.length,
    'Last-Modified': new Date(),
    'Expires': expiration,
    'ETag': null
  });

  res.json({ items: jsonTestData });
}
Run Code Online (Sandbox Code Playgroud)

以下是我针对此API方法执行的测试:

describe('GET /menu', function() {
  describe('HTTP headers', function() {
    it('responds with the right MIME type', function(done) {
      request(app)
        .get(apiPath + '/menu')
        .set('Accept', 'application/vnd.burgers.api+json')
        .expect('Content-Type', 'application/vnd.burgers.api+json; charset=utf-8')
        .expect(200, done); …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js supertest

11
推荐指数
2
解决办法
1万
查看次数