15 supertest - ranhs/soda-test GitHub Wiki
Note: This feture is only relevant for node applications, so it is only available when using mocha, and it is not available if using jest or karma
The supertest library gives a way to test REST server code that uses express, without really doning any networking calls.
Soda-Test gives you access to the request method of supertest for that.
In app.ts express route is defined as folow:
import * as express from 'express'
import { Express } from 'express'
import { urlencoded, json } from 'body-parser'
export const app: Express = express()
app.use(urlencoded({
extended: true
}))
app.use(json())
//-----------------------------------> routes
app.get('/', (req, res) => {
res.status(200).json({
name: 'Foo Fooing Bar'
})
})
We would like to test this default route, without realy using the web.
import { expect, describe, it, TR, request } from 'soda-test'
import { app } from './app'
@describe('app')
class AppTest {
@context('GET /')
@it('should get /')
async testGet1(): PTR {
const response = await request(app).get('/').expect(200)
expect(response.body).to.have.property('name').to.equal('Foo Fooing Bar')
}
}
Calling request on the express app object. On the return value to specific the route we what to check. In this case get('/'), and we expect it to return status of 200. By awaiting on the return value, we get the response and we can validate, for example, that the body of the response as a name propety with the value of 'Foo Fooing Bar'
The post route looks like this:
import { createUser } from './users'
app.post('/user', async (req, res) => {
try {
const result = await createUser(req.body)
res.json(result)
} catch (err) {
handleError(res, err)
}
})
To test it, on the request(app) call post and send to define the body of the request
@it('should call user.create')
async testPost1(@stub('./users', "createUser").resolves({name:'foo'}) createStub: SinonStub): PTR {
const response = await request(app)
.post('/user')
.send({name: 'fake'})
.expect(200)
expect(createStub).to.have.been.calledOnce
expect(response.body).to.have.property('name').to.equal('foo')
}
In a similar way you can test the delete route:
const response = await request(app).delete('/user/123').expect(200)
See supertest libraray for more information on what you can do with the request method