Currently, I am in the process of writing a test for a simple route within my API backend. This test is being written using Typescript and Jest, all within a docker container that I initiate using docker-compose
.
For my testing purposes, I have created a helper class which initializes an express webserver and establishes a connection to the database through the init function. In the shutdown function, it handles closing the connection as needed. My test script looks like this:
import { Helper } from "./helper";
import request from 'supertest'
describe('article', () => {
const helper = new Helper();
beforeAll(async () => {
await helper.init();
});
afterAll(async () => {
await helper.shutdown();
});
it('should test if reaching the api is possible', async (done) => {
request(helper.app)
.get('/test')
.send()
.set('Accept', 'application/json')
.expect(200)
.end( (error, response) => {
if(error) throw error;
expect(response.body.message).toBe("Hello");
});
});
To run the test, I use the following command:
"test": "jest --verbose --forceExit --runInBand --detectOpenHandles"
After executing the test, I observed the following output:
https://i.sstatic.net/eAkPt.png
Despite adjusting the Timeout settings as recommended, there was no change in behavior. To further investigate, I temporarily modified the route to return "Helloo" instead of the expected "Hello". The result was as follows:
https://i.sstatic.net/4KvMs.png
Evidently, the response is received. However, my concern lies with why the test appears to be running twice and consistently experiencing timeouts during the second test iteration.
Here is my jest.config.js
:
module.exports = {
"roots": [
"<rootDir>/src"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
"moduleFileExtensions": [
"ts",
"js"
],
}