-1

I'm trying to begin integration/unit testing for my nodejs api but I'm unable to properly connect to my app.js file via supertest.

The below code is written in my main.test.js file

const app = require('../app')
const supertest = require('supertest');
const request = supertest(app)

it('posts color', async () => {
    await request.post('/postColor')
    .send({
        "Color": "Green",
}).expect(201)
})

Below is my app.js file

import express from 'express';
const app = express();

export default app;

I broke apart my index.js file into an app.js and index.js file.

My index.js imports app from app.js and sets it up to listen to whichever port I need it to. My main.test.js file imports app from app.js and uses it as shown above in accordance with supertest.

I keep getting the following error

TypeError: app.address is not a function

  4 |
  5 | it('posts color', async () => {
> 6 |     await request.post('/postColor')
    |                   ^
Light
  • 75
  • 12
  • 2
    You're mixing export and require, you probably need to `require('../app').default`. But debugging to find out what `app` currently _is_ in the tests would help. – jonrsharpe May 25 '21 at 21:56
  • That helped, but it returns me to a previous issue where my api end point returns a 404 instead of a 201. I feel like there's something missing in the whole structure. @jonrsharpe – Light May 25 '21 at 22:01
  • 1
    Well that's a separate problem between your expectations of the server and the actual implementation. You'd have to give a [mre] as right now your example app doesn't have _any_ endpoints, so it'll always 404. – jonrsharpe May 25 '21 at 22:08
  • Hey @jonrsharpe check out my answer to this question. Let me know your thoughts. – Light May 25 '21 at 23:44

1 Answers1

1

I resolved this issue by adding the following to my main.test.js file:

const app = require('../app').default
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Light
  • 75
  • 12