• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

31
Views
How to test if function invoked inside Node.js API route has been called?

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()
})
about 1 month ago ·

Juan Pablo Isaza

Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.