• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

206
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 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

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

Andres GPT

Recommend me some offers
I have an error