标签: supertest

supertest test express中间件

发现以下关于如何在Express中测试中间件的提示:
https://github.com/visionmedia/express/blob/master/test/req.xhr.js
我想知道为什么我的测试总是通过.直到我注意到,当我从快递复制测试时,他们表现得一样.我试过拧紧它们但是它们不断传递:https: //github.com/visionmedia/express/blob/master/test/req.xhr.js

我在这里缺少什么?

it('should return true when X-Requested-With is xmlhttprequest', function(done){
  var app = express();

  app.use(function(req, res){
    req.xhr.should.be.false; //set to false, to fail the test but it still passes
    res.end();
  });

  request(app)
  .get('/')
  .set('X-Requested-With', 'xmlhttprequest')
  .end(function(res){
    done();
  })
})
Run Code Online (Sandbox Code Playgroud)

javascript testing node.js express supertest

6
推荐指数
1
解决办法
1846
查看次数

如何避免摩卡测试用例超时?

这里我附加了我的代码,我传递完成回调并使用supertest请求.因为我在request.end块中的testcase中使用assert/expect,为什么我需要担心超时?我在这里犯的是什么错误.

it('should get battle results ', function(done) {
    request(url)
      .post('/compare?vf_id='+vf_id)
      .set('access_token',access_token)
      .send(battleInstance)
      .end(function(err, res){  // why need timeout
        if (err) return done(err);
        console.log(JSON.stringify(res.body));
        expect(res.body.status).to.deep.equal('SUCCESS');
        done();
      });
 });
Run Code Online (Sandbox Code Playgroud)

响应后的测试用例结果:错误:超出2000ms的超时.确保在此测试中调用done()回调.

如果我使用mocha命令运行我的测试用例,那么它显示此错误,而如果我正在运行测试, mocha --timeout 15000 则testcase正确传递.但我想避免超时,我该怎么做?

unit-testing mocha.js node.js supertest

6
推荐指数
2
解决办法
5134
查看次数

编写使用supertest的测试时访问req.session对象

我刚刚开始在我的快速应用程序中使用中间件supertestnock为其编写单元测试。

首先检查我的路由器设置处理的所有请求是否存在会话属性(我正在使用Express-Session)。

app.use('/api', helpers.hasAccessToken, require('./routes.js'));
Run Code Online (Sandbox Code Playgroud)

助手只是这样做:

module.exports.hasAccessToken = function(req, res, next) {
  if(req.session.accessToken){
    next();
  } else {
    res.status(401).send('LOGIN_SESSION_ENDED');
  }
};
Run Code Online (Sandbox Code Playgroud)

在我的测试规范中,我有:

var app = require('./index.js'),
  request = require('supertest')(app),
  expect = require('chai').expect,
  nock = require('nock');


    describe('GET requests', function(){
      beforeEach(function(){
        nock('https://somedomain:port')
          .get('/someendpoint')
          .reply(200, {foo:'bar'});
      });
      it('should return a 200 HTTP status code', function(done){
        request
          .get('/api/someendpoint')
          .end(function(err, res){
            expect(res.status).to.equal(200);
            done();
          });
      });
    });
Run Code Online (Sandbox Code Playgroud)

相反,将返回状态为401的错误,我知道req.session.accessToken这取决于运行测试之前未设置的属性。

那么,如何才能使该req对象对会话对象执行我喜欢的操作?

谢谢

node.js express supertest

6
推荐指数
1
解决办法
404
查看次数

如何使用supertest和jest测试图像上传(流)?

我的API中有一个图像上传端点,它接受application/octet-stream请求并处理这些流.我想为这个端点编写测试覆盖,但无法弄清楚如何使用supertest来传输图像.

到目前为止,这是我的代码:

import request from 'supertest'

const testImage = `${__dirname}/../../../assets/test_image.jpg`

describe('Upload endpoint', () => {

  test('Successfully uploads jpg image', async () =>
    request(app)
      .post(`${ROOT_URL}${endpoints.add_image.route}`)
      .set('Authorization', `Bearer ${process.env.testUserJWT}`)
      .set('content-type', 'application/octet-stream')
      .pipe(fs.createReadStream(testImage))
      .on('finish', (something) => {
        console.log(something)
      }))

})
Run Code Online (Sandbox Code Playgroud)

这个代码什么都不产生,finish从不调用事件,没有任何控制台记录,并且这个测试套件实际上没有任何预期.我无法链接.expect到此请求,否则我得到此运行时错误:

TypeError:(0,_supertest2.default)(...).post(...).set(...).set(...).pipe(...).expect不是函数

这样的事情是如何完成的?

javascript streaming superagent supertest jest

6
推荐指数
1
解决办法
2380
查看次数

如何在超级测试中模拟中间件?

我想测试是否app.js调用了中间件。虽然我模拟了模块work.js,但它仍然运行原始代码。

应用程序.js

const work = require('./work')
const express = require('require')

const app = express()
  .use(work)
  .use(...)
  .get(...)


module.exports = app
Run Code Online (Sandbox Code Playgroud)

工作.js

function work(req, res, next){...}

module.exports = work
Run Code Online (Sandbox Code Playgroud)

app-test.js

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

test('test middleware in app.js', async(done) => {
  jest.mock('../work', () => jest.fn((req, res, next) => next()))

  const agent = () => supertest(app)
  const work = require('../work')  

  await agent()
    .get('/')
    .set(...)

  expect(work).toHaveBeenCalledTimes(1)  // Error

  done()
})

Run Code Online (Sandbox Code Playgroud)

我希望这work.js会被调用一次。有什么不对的吗?我应该改变我的测试吗?

node.js express supertest jestjs

6
推荐指数
1
解决办法
9877
查看次数

未找到 supertest 错误测试快速端点

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

索引.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}!`));
Run Code Online (Sandbox Code Playgroud)

和 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);
      });
  });
});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我收到此错误。 err Error: expected 200 "OK", got 404 "Not Found"

怎么了?

我在浏览器中访问 …

node.js express supertest jestjs

6
推荐指数
1
解决办法
2845
查看次数

Jest 不等待 async beforeAll 完成

我正在尝试测试从我的 REST API 获取所有用户。

describe('GET', () => {
    let userId;

    // Setup create the mock user
    beforeAll(async () => {
      //Create the user
      return await request
          .post(routes.users.create)
          .set('Accept', 'application/json')
          .send(TEST_USER_DATA)
          .then(res => userId = res.body.id)
    })

    // Clean up, deleting all the fake data that we created for this test suite
    afterAll(async () => {
      // Clean up, delete the user we created
     return await request.delete(routes.users.delete(userId));
    })

    it('should get all users', async () => {
      const usersResponse = await request …
Run Code Online (Sandbox Code Playgroud)

asynchronous supertest jestjs e2e-testing

6
推荐指数
0
解决办法
2850
查看次数

Jest、TypeScript 和 ts-jest:语法错误:无法在模块外部使用 import 语句

我正在使用 Jest 和 SuperTest 测试 Apollo 服务器。服务器是用 TypeScript 编写的,所以我使用ts-jest. 我需要将 SuperTest 绑定到特定端口。SuperTest 文档说

\n\n
\n

您可以将 http.Server 或函数传递给 request() - 如果服务器尚未侦听连接,则它会为您绑定到临时端口,因此无需跟踪端口。

\n
\n\n

所以我想传递我的应用程序。我已经设置了索引文件来导出 Apollo 服务器

\n\n
// index.ts\nimport { ApolloServer } from \'apollo-server\';\n...\nconst start = () => {\n    ...\n    const server = new ApolloServer(config);\n    server.listen().then(({ url }) => {\n        log.info(`interface server  Running at ${url}`);\n    });\n    return server;\n};\n\nconst app = start();\n\nexport default app;\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是当我运行我的代码时

\n\n
// __test__/index.ts\nimport { default as request } from \'supertest\';\nimport log from \'../util/log\';\nimport …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing typescript supertest jestjs

6
推荐指数
0
解决办法
1003
查看次数

Mochawesome 包含 javascript 代码而不是 typescript

我使用 mocha + supertest 在 Typescript 中编写了一些 api 测试。我仅使用“ts”文件运行测试,方式如下:

"api:test": "cross-env TS_NODE_PROJECT='tsconfig.api.json' mocha -r ts-node/register 'test/api/**/*.ts' --reporter mochawesome  --reporter-options overwrite=false,html=false,json=true,reportDir='test/api/report/mochawesome-report'",
Run Code Online (Sandbox Code Playgroud)

在生成的报告中包含测试的代码片段,但不是来自 ts 文件,而是来自转译的 js 文件。 在此输入图像描述

有没有办法包含打字稿代码而不是javascript?

提前致谢!

javascript mocha.js typescript supertest mochawesome

6
推荐指数
0
解决办法
310
查看次数

Express Jest 和 Supertest 如何用参数模拟中间件

我已经尝试了几个小时,用 Jest、Supertest 和 Express 测试我的 Rest api 的端点。

该端点受到名为“ ”的身份验证中间件的保护advancedAuthGuard

所以我试图模拟这个中间件,以便跳过端点测试的身份验证检查

//./router.js 
router.get('/route1', advancedAuthGuard(false), controller);
Run Code Online (Sandbox Code Playgroud)

重要:advancedAuthGuard是一个接受配置参数的中间件(柯里化中间件)

//./middleware/advancedAuthGuard.js
const advancedAuthGuard = (additionalCondition) => (req,res,next) => {

  //Check authentication logic ...
  const isAuth = true

  if (isAuth && !additionalCondition)
    next()
  else
    next(new Error('Please auth'))
}
Run Code Online (Sandbox Code Playgroud)

当我运行以下测试来检查是否收到状态代码 '200' 时。测试在运行前失败。

//./test.js
import supertest from "supertest"
import app from './app.js'
import { advancedAuthGuard } from "./middlewares/advancedAuthGuard";

jest.mock("./middlewares/advancedAuthGuard")

const request = supertest(app)

beforeEach(()=>{
  jest.clearAllMocks()
})

it("should '/route1' respond with 200 …
Run Code Online (Sandbox Code Playgroud)

mocking node.js express supertest jestjs

6
推荐指数
1
解决办法
4481
查看次数