问题
I have been using mocha
, supertest
and proxyquire
since last few days.
I am able to do integration test with no problem. But I have some questions.
This is one test suite from my project.
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')
})
})
So here I want to know.
What's the role of mocha here?
I know with supertest
I can make http requests.
But for each test suite I am passing an instance of express app.
So, What's supertest doing with that express app?
Does it create new server each time to make requests?
..and If so, is it possible to create just one express server for each test suite?
回答1:
Yes, each time you pass an express app to supertest, it runs an express server for you, and if you want to create an express server and use it in some unit tests, you can do it in before section to create a server and use it multiple times. Beside that, I suggest you to check rest-bdd-testing module, it's so simple with some nice features for testing REST APIs.
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')
})
})
来源:https://stackoverflow.com/questions/60664141/does-mocha-supertest-create-express-server-for-each-test-suite