标签: supertest

玩笑/超级测试错误 - “instanceof”的右侧不可调用

当像这样使用超级测试时,

import app from "../../src/app";
import request from "supertest";

describe("GET / - a simple api endpoint", () => {
  it("Hello API Request", () => {
    const result = request(app)
    .get("/api/location/5eda6d195dd81b21a056bedb")
    .then((res) => {
      console.log(res);
    })
    // expect(result.text).toEqual("hello");
    // expect(result.status).toEqual(200);

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

我越来越"Right-hand side of 'instanceof' is not callable"

 at Response.toError (node_modules/superagent/lib/node/response.js:94:15)
      at ResponseBase._setStatusProperties (node_modules/superagent/lib/response-base.js:123:16)
      at new Response (node_modules/superagent/lib/node/response.js:41:8)
      at Test.Request._emitResponse (node_modules/superagent/lib/node/index.js:752:20)
      at node_modules/superagent/lib/node/index.js:916:38
      at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/parsers/json.js:19:7)
      at processTicksAndRejections (internal/process/task_queues.js:84:21) {
          status: 500,
          text: `"Right-hand side of 'instanceof' is …
Run Code Online (Sandbox Code Playgroud)

express supertest

8
推荐指数
1
解决办法
7804
查看次数

如何使用supertest和agent在mocha测试中进行身份验证请求?

401 Unauthenticated在登录后无法运行经过身份验证的测试(服务器返回).

var should = require('should'),
    _ = require('lodash'),
    app = require('../../../server'),
    mongoose = require('mongoose'),
    User = mongoose.model('User'),
    request = require('supertest');

var user
    , user1;

describe('GET /api/jobs', function () {
    before(function (done) {
        user = new User({
            provider: 'local',
            name: 'Fake User',
            email: 'test@test.com',
            password: 'password'
        });

        // Clear users before testing
        User.remove().exec();

        request(app)
            .post('/api/users')
            .send(user)
            // end handles the response
            .end(function(err, res) {
                if (err) {
                    throw err;
                }

                res.should.have.status(200);
                res.body._id.should.exist;

                user1 = request.agent(app); //user1 will be …
Run Code Online (Sandbox Code Playgroud)

tdd restful-authentication mocha.js node.js supertest

7
推荐指数
1
解决办法
7418
查看次数

获取"错误:字符串"不是有效的BCrypt哈希."在Mocha ExpressJS测试期间抛出了一个错误:)"

我有一个使用Passport进行身份验证的MEAN堆栈应用程序.

我正在尝试编写一个登录的单元测试,并检查是否重定向到root(/).但是,每当我运行Mocha时,我都会收到以下错误消息:

1) POST /home Login test should redirect to / after login:
   Error: the string "Not a valid BCrypt hash." was thrown, throw an Error :)
Run Code Online (Sandbox Code Playgroud)

这是我的单元测试LoginSpec.js:

var should = require("should");
var app = require("../app");
var mongoose = require("mongoose");
var User = mongoose.model("User");
var request = require("supertest");
var agent = request.agent(app);
...
describe('POST /home', function() {
    before(function(done) {
        user = new User({
            email: "john@email.com",
            firstName: "John",
            lastName: "Doe",
            password: "strongPassword",
            username: "johndoe"
        });

        user.save(done);
    }) …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js express supertest passport.js

7
推荐指数
1
解决办法
6644
查看次数

超级测试预期未正确断言状态代码

我有一个如下所示的测试:

  it('should fail to get deleted customer', function(done) {
    request(app)
      .get('/customers/'+newCustomerId)
      .set('Authorization', 'Bearer ' + token)
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(404, done)
  });
Run Code Online (Sandbox Code Playgroud)

我已阅读此处的文档:

https://github.com/visionmedia/supertest

它是这么说的:

请注意如何将 did 直接传递给任何 .expect() 调用

不起作用的代码行是.expect(404, done)如果我将其更改为.expect(200, done)那么测试不会失败。

但是,如果我添加这样的结尾:

  it('should fail to get deleted customer', function(done) {
    request(app)
      .get('/customers/'+newCustomerId)
      .set('Authorization', 'Bearer ' + token)
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
          if (err) console.log(err);
          done();
      });
  });
Run Code Online (Sandbox Code Playgroud)

然后测试失败。为什么.expect(200, done)也不失败呢?

node.js jasmine supertest

7
推荐指数
1
解决办法
5180
查看次数

测试成功完成后,Jest不会终止

我正在使用jest&supertest测试我的api端点,测试正在通过,没有任何问题; 然而,我jest永远不会退出我通常会看到的X时间表中Done.我希望确保--watch标志没有被使用,但事实并非如此.似乎与服务器的连接永远不会结束,所以jest不知道下一步是什么.UserFactory.generate()使用faker库创建虚假用户数据.

我在试图解决这个问题时感到很茫然.我已经按照推荐的策略在jest帮助页面上运行,没有运气,也在问题跟踪器中挖掘,但没有看到类似的问题.

这是我在运行测试套件时会看到的:

在此输入图像描述

正如您所看到的那样,测试运行了7次.我被告知所有测试都已运行,然后morgan显示POST已发生的情况.jest永远不会退出,所以实际上这是失败的,因为它会在任何CI服务器超时,除非手动退出.

我尝试过使用.end() & done()以及.then() & done()代替async/await.他们都返回相同的最终结果,如果这是一个未解决的承诺的问题,jest将会因为未解决的承诺而出错,所以我无法理解为什么这不会像jest通常那样终止.

以前有人遇到过这样的问题吗?

user.controller.test.js

import mongoose from 'mongoose';
import request from 'supertest';
import { UserFactory } from '../../__mocks__';
import { User } from '../../modules';
import { config } from '../../utils';
import app from '../../'; …
Run Code Online (Sandbox Code Playgroud)

supertest jestjs

7
推荐指数
1
解决办法
5325
查看次数

Jest&amp;supertest API 测试返回 TypeError: app.address is not a function

我目前正在制作一个带有打字稿、节点、快递的 API,并使用 jest 和 supertest 进行测试。我在使用 Javascript 时没有问题,但我最近将我的项目文件从 JS 更改为 TS,包括测试文件,当我开始测试时,我在所有测试套件中的超级测试请求部分都收到以下错误,这是其中之一当我开始测试时,我的终端上的测试套件。

  TypeError: app.address is not a function

  37 |     it("should return 400 if email is invalid", async () => {
  38 |       const res = await request(server)
> 39 |         .post("/api/users/auth/register")
     |          ^
  40 |         .send({
  41 |           email: "nomail",
  42 |           password: "validpassword123",
Run Code Online (Sandbox Code Playgroud)

这是我的测试文件auth.test.ts

import * as request from 'supertest';
import { User } from '../../../../src/models/User';
import * as mongoose from 'mongoose';
import getKeys from '../../../../src/config/keys';

describe("/api/users/auth", …
Run Code Online (Sandbox Code Playgroud)

express typescript supertest jestjs

7
推荐指数
1
解决办法
3422
查看次数

如何在 NodeJS 中测试服务器发送事件 (SSE) 路由?

我的 NodeJS 应用程序上有一个 Server Sent Events 路由,客户端可以订阅该路由以从服务器获取实时更新。它看起来像这样:

router.get('/updates', (req, res) => {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    })

    const triggered = (info) => {
        res.write(`\ndata: ${JSON.stringify(info)}\n\n`)
    }

    eventEmitter.addListener(constants.events.TRIGGERED, triggered)

    req.on('close', () => {
        eventEmitter.removeListener(constants.events.TRIGGERED, triggered)
    })
})
Run Code Online (Sandbox Code Playgroud)

supertest在节点中使用测试传统路由非常简单:

test('Should get and render view', async() => {
    const res = await request(app)
        .get('/')
        .expect(200)

    expect(res.text).not.toBeUndefined()
})
Run Code Online (Sandbox Code Playgroud)

但是,这在测试 SSE 路由时不起作用。

有没有人对如何使用 Node 测试 SSE 路由有任何想法?它不一定必须使用supertest. 只是寻找有关如何测试它supertest或其他方式的想法。

编辑: 我有一个关于如何集成测试的想法。基本上,必须在测试前启动服务器,在测试期间订阅它并在测试后关闭它。但是,当我使用 beforeEach() 和 afterEach() 启动服务器时,它在 Jest 中无法按预期工作。

node.js server-sent-events supertest

7
推荐指数
1
解决办法
1804
查看次数

节点 EADDRINUSE:使用 jest 和 supertest 进行测试时,地址已在使用 :::3000

我正在尝试使用 jest 和 supertest 测试我的 API 端点:

我的测试路线文件:

const app = require('../../index') 
const request = require('supertest')


describe('test app endpoints', ()=>{
    test('index should return 200 code', async (done) =>{
        const response = await request(app).get('/')
        expect(response.statusCode).toBe(200)
        done()
    })
Run Code Online (Sandbox Code Playgroud)

索引.js:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

const port = 3000


app.set('view engine', 'ejs')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use('/', require('./routes/conversions'))

module.exports = app.listen(port, (err) => {
    if (err) throw err
    console.log(`Server is running on port ${port}`)
}) …
Run Code Online (Sandbox Code Playgroud)

javascript node.js supertest jestjs

7
推荐指数
2
解决办法
4049
查看次数

在 jest 中运行 e2e 测试时无法 POST /graphql (404) 错误(GraphQL Federation)

我正在尝试在 Nest.js 应用程序中使用 supertest + jest 端到端测试我的 graphql 服务,但不断收到此错误:

错误:无法 POST /graphql (404)

我尝试了很多方法,但由于该错误而无法使测试完全运行。

下面是我的测试文件:

import request from 'supertest';
import { INestApplication } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { GatewayAppModule } from '../../../app-gateway.module';
import { AppModule } from '../../../app.module';
import { CreateAccountArgs } from '../dto/create-account.args';

jest.mock('graphql-moment', () => ({
  GraphQLDate: jest.fn(),
}));

describe('Auth resolver: Authentication module e2e test', () => {
  let mainApp: INestApplication;
  let gatewayApp: INestApplication;

  beforeAll(async () => {
    const mainAppModuleRef: TestingModule = …
Run Code Online (Sandbox Code Playgroud)

supertest jestjs graphql nestjs graphql-federation

7
推荐指数
0
解决办法
694
查看次数

如何使用 serverless-offline 和 Supertest 从集成测试中获取代码覆盖率指标?

我正在构建一个 AWS Lambda 函数并尝试为其编写一些集成测试。Lambda 函数使用无服务器离线插件在本地运行,并且只需接收带有一些查询参数的 GET 请求。我使用 Jest 和 Supertest 编写集成测试,如下所示:

import request from 'supertest';

describe('User position handler', () => {
    it('should return history', () => {
        const server = request('http://0.0.0.0:4000');
        return server
            .get(`/local/position?type=month&period=3`)
            .expect(200)
            .expect((response) => {
                console.log('RESPONSE', response);
                expect(response.body).toHaveLength(3);
            });
    });
});
Run Code Online (Sandbox Code Playgroud)

问题是,当我使用收集覆盖率选项运行 Jest 时,通过 Supertest 发送的请求到达的代码不会在指标中计算。运行jest --collectCoverage结果是:

代码覆盖率结果

问题是,我知道,例如,infra/handlers/user-position.ts正在达到并覆盖超过 0% 的语句,但覆盖率指标并未按预期显示。另外,我知道user-monthly-position.service.impl.ts在流程的某个点已经达到了这一点,因为该服务负责从外部服务返回数据,并且 Supertest 的响应正在返回数据。绿线来自单元测试覆盖的文件,这些文件仅使用 Jest(显然不是 Supertest)

我知道当将 Supertest 与 Express 框架一起使用时,我可以传递 Express 应用程序的实例。到request函数。这样我认为 Jest 可以“检查”或“检测”函数调用堆栈来测量覆盖率(下面的代码示例)。但是如何传递正在运行的serverless-offlineLambda 的 URL …

amazon-web-services supertest jestjs serverless-framework serverless-offline

7
推荐指数
1
解决办法
880
查看次数