I have a simple test script for my API, the specific route is not implemented at the moment. But for some reason tests pass. Here is the script:
const request = require('supertest')
const api = require('../api-server')
// testing data:
const pmOne = {
name: "Some Name",
tel: "234 123"
}
const pmTwo = {
name: "Some Other Name",
tel: "256 789"
}
describe('Basic CRUD API', () =>{
it('GET /pm --> array of all projectmanagers', () =>{
request(api)
.post('/pm')
.send(pmTwo)
.expect(207)
})
it('GET /pm/id --> new projectmanager', () => {
request(api)
.get('/pm/' pmOneId)
.expect(200)
.then((res) => {
expect(res.body.name).toBe(pmOne.name)
expect(res.body.tel).toBe(pmOne.tel)
})
})
And here is my app.js:
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const app = express()
const pmRouter = require('./routes/pm.router')
// establish mongodb connection
var options = {
user: process.env.DATABASE_USER,
pass: process.env.DATABASE_PASSWD
}
mongoose.connect(process.env.DATABASE_URL, options)
const db = mongoose.connection
db.on('error', (error) => console.error(error))
app.use(express.json())
//app.use('/pm', pmRouter)
module.exports = app
The
//app.use('/pm', pmRouter)
Is commented out, so the route is not valid. That means all request should return 404 (which they do), so why am I getting passes on my tests:
> jest --forceExit --runInBand
PASS tests/projectmanager.test.js
Basic CRUD API
✓ GET /pm --> array of all projectmanagers (5 ms)
✓ GET /pm/id --> new projectmanager (3 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 0.571 s, estimated 1 s
Ran all test suites matching /tests\/projectmanager.test.js/i.
Force exiting Jest: Have you considered using `--detectOpenHandles` to detect async operations that kept running after all tests finished?
CodePudding user response:
Supertest request returns a promise and if you want to assert the returned value it has to be awaited or returned explicitly.
Either return it or use async/await
syntax.
In your case simply add a return
statement.
it('GET /pm', () => {
return request(api).post('/pm').send(pmTwo).expect(207)
});