标签: supertest

设置超时,超时无效

我正试图用一些代码来测试我的服务器:

describe 'POST /do/some/stuff/', ->
  it 'should do this thing', (done) ->
    request app
      .post '/do/some/stuff/'
      .timeout 10000
      .expect 200
      .end (err, res) ->
        return done err if err?
        done()
Run Code Online (Sandbox Code Playgroud)

服务器正在做的事情通常需要几秒钟,这比默认超时2000毫秒长,所以我打电话.timeout 10000.但是,尽管如此,当我运行代码时,我得到:

1) POST /do/some/stuff/ should do this thing:
   Error: timeout of 2000ms exceeded
Run Code Online (Sandbox Code Playgroud)

我需要做些什么来增加此超时?

mocha.js node.js supertest

4
推荐指数
1
解决办法
5637
查看次数

是否可以使用hapi的supertest?

我正在使用hapi,而不是表达.supertest还应该工作吗?

如果是这样,是否有一种快速方法来更改我的代码以使其运行?

根据文档,我的测试看起来像这样:

import tape = require('tape');
const supertest = require('supertest');
const app = require('../../../../src/app');

tape('creates new user in database', function (assert) {
  supertest(app)
    .get('/ekapi/v1/signup')
    .expect(200)
    ......
});
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

dist/server/app/node_modules/supertest/lib/test.js:55
  var addr = app.address();
                 ^

TypeError: app.address is not a function
    at Test.serverAddress (/home/rje/projects/ekaya/dist/server/app/node_modules/supertest/lib/test.js:55:18)
Run Code Online (Sandbox Code Playgroud)

这是我的应用代码:

app.ts

import './core/externalTypes/imports';
import 'reflect-metadata';
import kernel from './core/inversify.config';
import {IServer}  from './core/types/IServer';

let server = kernel.get<IServer>("IServer");
server.start();
Run Code Online (Sandbox Code Playgroud)

server.ts

import _ = require('lodash');
import * as hapi from "hapi";
import { injectable, inject …
Run Code Online (Sandbox Code Playgroud)

supertest hapijs

4
推荐指数
2
解决办法
1523
查看次数

摩卡测试永远运行

大家好,感谢您的关注。

我正在尝试使用 mocha 和 supertest 运行测试,即使一切正常,测试也会永远运行。为了避免这种情况,我在 after() 方法中添加了一个“process.exit(0)”,因此它可以正确构建,但这对于“隔离”来说似乎是错误的(此外,它看起来很糟糕:-))

我的 package.json:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "nodejs ./bin/www",
    "test": "mocha"
  },
  "dependencies": {
    "body-parser": "~1.0.0",
    "cookie-parser": "~1.0.1",
    "debug": "~0.7.4",
    "ejs": "~0.8.5",
    "express": "~4.0.0",
    "is-my-json-valid": "^2.16.1",
    "knex": "^0.13.0",
    "morgan": "~1.0.0",
    "mysql": "^2.14.1",
    "static-favicon": "~1.0.0"
  },
  "devDependencies": {
    "mocha": "^4.0.0",
    "supertest": "^3.0.0",
    "chai": "^4.1.2",
    "util": "^0.10.3"
  }
}
Run Code Online (Sandbox Code Playgroud)

我的测试:

var request = require('supertest');
var util    = require('util');

describe('Endpoints', function () {
  var server;

  beforeEach(function() {
    server = require('../app').listen(3000); …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js supertest

4
推荐指数
2
解决办法
3119
查看次数

即使响应正确,使用 supertest 和 jest 测试 API 错误也会失败

我正在使用jest 23.1.0supertest 3.1.0。我正在为后端编写一些测试,一切进展顺利,但是对于特定路由的特定情况,即使响应对象似乎包含正确的信息,测试也会失败。测试是检查参数是否是有效的 JSON,如下所示:

\n\n
describe(\'GET /graph\', () => {\n    it(\'invalid JSON\', (done) => {\n        request(app)\n            .get(\'/graph\')\n            .set(\'Accept\', \'application/json\')\n            .expect(\'Content-Type\', /json/)\n            .expect(415)\n            .then(done);\n        });\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

在这种情况下,我实际上根本没有发送任何参数,但即使我确实发送了一些无效的 JSON,问题也是一样的。无论如何,这两种情况都会触发相同的后端检查,即:

\n\n
module.exports = (req, res, next) => {\n\n    let dataParameters;\n    try {\n        dataParameters = JSON.parse(req.query.dataParameters);\n    }\n    catch(error) {\n        return(res.status(415).send({\n            message: "Request parameters are not a valid JSON object",\n            other: `${error.name} - ${error.message}`\n        }));\n    }\n    ...\n
Run Code Online (Sandbox Code Playgroud)\n\n

当我运行 jest 时,测试失败,控制台的输出如下:

\n\n
  GET /graph\n    \xe2\x9c\x95 invalid JSON (6ms)\n\n  \xe2\x97\x8f GET /graph …
Run Code Online (Sandbox Code Playgroud)

testing http node.js supertest jestjs

4
推荐指数
1
解决办法
4497
查看次数

如何使用 Jest 和 Supertest 在每次测试之间清除 cookie?

我有一套测试,如果单独运行,它们都会通过。但是,如果并行运行,测试会由于检查 cookie 的值而失败。

问题是 supertest 的 cookie 在每次测试之间都不会被清除。

有没有办法使用 supertest 在每次测试之间清除 cookie?这与这个未提供解决方案的未解决问题有关。

我都尝试过:

afterEach(() => {
  request(app)
    .set('Cookie', [])
})
Run Code Online (Sandbox Code Playgroud)

和:

afterEach(() => {
  request(app)
    .set('Cookie', '')
})
Run Code Online (Sandbox Code Playgroud)

...没有用。

以下是单独运行良好但并行运行时失败的两个测试:

test('It should respond 302 to the wrong url', (done) => {
  const accessiblePages = {get_member_accessible_pages: []}
  nock('http://localhost:8000')
    .log(console.log)
    .get('/auth/me/')
    .reply(200, accessiblePages)
  // Must use j: to work with cookie parser
  const cookie = 'userInfo=j:' + encodeURIComponent(
    JSON.stringify(accessiblePages))
  request(app)
    .get('/first-url')
    .set('Cookie', cookie)
    .expect(302)
    .expect('Location', '/new-url')
    .then((response) => {
      expect(response.statusCode).toBe(302) …
Run Code Online (Sandbox Code Playgroud)

superagent supertest reactjs jestjs

4
推荐指数
1
解决办法
8465
查看次数

使用 Supertest 时收到 500“内部服务器错误”

因此,我过去从未在我的所有项目中实际实施过任何测试,并决定开始在我正在开发的新项目中实施它。作为一个完全的初学者,我对得到的输出有点困惑。

当我使用邮递员时。它不会返回 500 错误,而是将信息保存到后端。运行测试时遇到的错误是

1) POST /users
       Creates a new user:
     Error: expected 200 "OK", got 500 "Internal Server Error"
Run Code Online (Sandbox Code Playgroud)

我还将展示我的代码是什么样子,以便希望找出我出错的地方。

// 测试

var express = require("express");
var request = require("supertest");
var app = express();
let router = require("../../server/routes/api/users");

app.use(router);

describe("GET /test", function() {
  it("Returns a json for testing", function(done) {
    request(app)
      .get("/test")
      .set("Accept", "application/json")
      .expect("Content-Type", /json/)
      .expect(200, done);
  });
});

describe("POST /users", () => {
  let data = {
    name: "dummy",
    email: "dummy@dummy.com",
    password: 123456
  };

  it("Creates a new …
Run Code Online (Sandbox Code Playgroud)

testing mocha.js node.js chai supertest

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

Jest Expect 无法捕获 async wait 函数的 throw

我正在使用 MongoDB 和 Mongoose 测试 typescript-express ap。对于此测试,我使用 jest 和 mongo-memory-server。我可以测试插入新文档并将现有文档检索到数据库中,但当文档不存在时我无法捕获错误。

const getUserByEmail = async (email: string): Promise<UserType> => {
  try {
    const user = await User.findOne({ email });
    if (!user) {
      const validationErrorObj: ValidationErrorType = {
        location: 'body',
        param: 'email',
        msg: 'User with this email does not exist!',
        value: email,
      };
      const validationError = new ValidationError('Validation Error', 403, [
        validationErrorObj,
      ]);
      throw validationError;
    }
    return user;
  } catch (err) {
    throw new Error(err);
  }
};


let mongoServer: any;
describe('getUserByEmail', (): …
Run Code Online (Sandbox Code Playgroud)

integration-testing express typescript supertest jestjs

4
推荐指数
1
解决办法
4219
查看次数

如何从 Jest 中的超级测试请求中检索 cookie?

我刚刚开始使用 Jest,正在尝试测试端点POST/register。该端点发回 2 个 cookie:accessToken:*jwt*refreshToken:*jwt*

这是我的测试文件:

import server from "../server"
import supertest from "supertest"
import mongoose from "mongoose"

import dotenv from "dotenv"
dotenv.config()

const request = supertest(server)

describe("Testing Auth endpoints", () => {
  beforeAll(done => {
    const PORT = process.env.PORT
    mongoose
      .connect(process.env.MONGO_STRING_TEST!)
      .then(() => {
        console.log("Connect to Atlas. Test DB.")
        done()
      })
      .catch(err => console.log(err))
  })

  const validUser = {
    name: "Paul Stevens",
    email: "ps@g.com",
    password: "1234",
    role: "host",
  }

  it("should test /register for …
Run Code Online (Sandbox Code Playgroud)

cookies typescript supertest jestjs

4
推荐指数
1
解决办法
3288
查看次数

grunt测试api与supertest,express和mocha

我有一个运行快递的https服务器,我使用mocha和supertest进行测试.

我的问题是 - 如果我只运行测试 - 它确定.如果我尝试运行带有测试的gruntfile然后运行express - 我看到很多EADDRINUSE错误,即使在测试文件中我用app.close()做后().同样适用于测试中的观察任务.

这是我的exapmle测试:

/* jshint node: true*/
/*global describe, it, after*/
(function() {
    'use strict';
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var request = require('supertest');
    var app = require('../server.js').app;
    var expect = require('chai').expect;
    var Cookies;

    after(function(done) {
        app.close();
        setTimeout(function(){done();}, 1500);
    });

    describe('/login', function() {
        it('should auth the user', function(done) {
            request(app)
                .post('/login')
                .send({login: "test", password: 'test'})
                .expect(302)
                .end(function(err, res) {
                    expect(err).to.be.equal(null);
                    expect(res.text).to.be.equal("Moved Temporarily. Redirecting to /");
                    Cookies = res.headers['set-cookie'].pop().split(';')[0];
                    done();
            });

        });
    });
    // testing API for …
Run Code Online (Sandbox Code Playgroud)

unit-testing mocha.js node.js express supertest

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

如何触发Express错误中间件?

我正在尝试对Mocha中的这段代码进行单元测试:

app.use(function (err, req, res, next) {
    console.error(err.stack)
    res.status(500).send('Something broke!')
})
Run Code Online (Sandbox Code Playgroud)

我不知道如何在Mocha单元测试中获取我的请求以触发它。

unit-testing mocha.js node.js express supertest

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