【问题标题】:Does mocha/supertest create express server for each test suite?mocha/supertest 是否为每个测试套件创建快速服务器?
【发布时间】:2020-06-25 02:18:47
【问题描述】:

从最近几天开始,我一直在使用 mochasupertestproxyquire

我能够毫无问题地进行集成测试。但我有一些问题。

这是我项目中的一个测试套件。

const expect = require('chai').expect
const request = require('supertest')
const _ = require('lodash')
const sinon = require('sinon')
const faker = require('faker')



describe('ComboController  /api/v1/combos', function () {
    const app = require('../src/app')
    it('should GET combo of given id: getComboById', async () => {
        const response = await request(app)
            .get(`/api/v1/combos/${faker.random.alphaNumeric(1)}`)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(200)
        const body = response.body
        expect(body).to.have.keys('status', 'message', 'data')
        expect(body.status).to.be.a('Boolean').true
        expect(body.data).to.be.a('Object')
    })
})

所以在这里我想知道。

摩卡在这里的作用是什么?

我知道 supertest 我可以发出 http 请求。

但是对于每个测试套件,我都传递了一个 express 应用程序的实例。


那么,supertest 对那个 express 应用程序做了什么?

每次发出请求时都会创建新服务器吗?


..如果是这样,是否可以为每个测试套件只创建一个快速服务器?

【问题讨论】:

    标签: node.js express mocha.js supertest


    【解决方案1】:

    是的,每次你将 express 应用程序传递给 supertest 时,它都会为你运行一个 express 服务器,如果你想创建一个 express 服务器并在一些单元测试中使用它,你可以在之前的部分中创建一个服务器并多次使用它。 除此之外,我建议您检查rest-bdd-testing 模块,它非常简单,具有一些用于测试 REST API 的不错的功能。

    describe('ComboController  /api/v1/combos', function () {
        let server;
        const app = require('../src/app')
        
        before(()=> {
            server = request(app);
        });
       
        it('should GET combo of given id: getComboById', async () => {
            const response = await server;
                .get(`/api/v1/combos/${faker.random.alphaNumeric(1)}`)
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect(200)
            const body = response.body
            expect(body).to.have.keys('status', 'message', 'data')
            expect(body.status).to.be.a('Boolean').true
            expect(body.data).to.be.a('Object')
        })
    })

    【讨论】:

    • 如果它在监听哪个端口创建服务器?
    • 每次它在临时端口上创建服务器并在该端口上侦听。顺便说一句,您的问题是超测 github 页面中的open issue,我建议您访问该问题。
    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 2019-10-01
    • 1970-01-01
    相关资源
    最近更新 更多