0

I'm using Node.js and Express to set up API route.
A route calls a function on an HTTP request.
I want to test if that function has been called.

When I'm making an HTTP request (using Axios, fetch, whatever) inside a test suite, I'm only able to test the HTTP response.

Any ideas on how to overcome this problem?

temp.js module

function testFn() {
  console.log("I just want to test if this fn has been called")
}

module.exports = {
  testFn,
}

Express app (that runs in the background)

const { testFn } = require("./temp")

app.get('/test', (req, res) => {
  testFn()
  res.send('GET request')
})

My approach to testing which obviously doesn't work (it's not unit testing)

const { default: axios } = require("axios")
const { testFn } = require("./temp")

jest.mock("./temp", () => ({
  testFn: jest.fn(),
}))

test("API test", async () => {
  await axios.get(`http://localhost:3000/test`)
  expect(testFn).toHaveBeenCalled()
})
Adrian Bienias
  • 829
  • 10
  • 16
  • 1
    You could test that console.log was called with "I just want to test..." See https://stackoverflow.com/a/59225389/294949 – danh May 11 '22 at 20:53
  • 1
    `jest.mock()` will be applied (and you'll be able to check that `testFn` was called) if your express app is started and stopped by your test (not running separately in background as it is now). [supertest](https://github.com/visionmedia/supertest) might be useful for testing Express and can start a server and bind it to random port for you. – Vitalii May 11 '22 at 22:22
  • Thanks for bringing that idea @danh, it can work but that console.log was just an example. In my real functions, I don't log their invocation to the console. Of course, I could add it but that's not ideal. – Adrian Bienias May 12 '22 at 08:47
  • @Vitalii I was thinking about using supertest but I thought it won't make a difference - thanks for that advice, I'll try that library. – Adrian Bienias May 12 '22 at 08:48
  • Thanks again @Vitalii, using superset helped. Feel free to add an answer and I'll accept it as solving the problem. – Adrian Bienias May 12 '22 at 10:26

0 Answers0