I am attempting to write some simple tests for my backend, and I am following a tutorial where a very similar code functions, while mine does not (he gets no complain about his app.use()). Why does it throw TypeError: app.use() requires a middleware function, and what can I replace my current code with to get it to run my test?
Here is my code:
const express = require('express');
const request = require('supertest');
const app = express();
const api = require('../server');
// make api available
app.use(api);
//app.use(bodyParser);
describe('games', () => {
it('should return a saved game', () => {
// send a request
return request(app)
.post('/games')
.send({title: 'test', released: '1995'})
// verify response
.expect(201)
.expect(res => {
const game = res.body;
expect(game.title).toEqual('test');
expect(game.released).toEqual('1995');
});
});
});
Here is the error from the console:
"C:\Program Files\nodejs\node.exe" C:\Users\Bertinator\Desktop\web-exam\node_modules\react-scripts\scripts\test.js --colors --setupTestFrameworkScriptFile "C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.4\plugins\JavaScriptLanguage\helpers\jest-intellij\lib\jest-intellij-jasmine.js" --testPathPattern ^C:\\Users\\Bertinator\\Desktop\\web\-exam\\src\\backend\\__tests__\\game\.jest\.js$
FAIL src\backend\__tests__\game.jest.js
● Test suite failed to run
TypeError: app.use() requires a middleware function
at Function.use (node_modules/express/lib/application.js:210:11)
at Object.<anonymous> (src/backend/__tests__/game.jest.js:10:5)
at <anonymous>
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.761s
I fixed it by adding
module.exports = app;
To my server.js. Jest was not able to use it as a valid middleware, hence the error.