Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
How to mock a particular method of a class in jest?

In the provided code, I have a class with a method that concats a string. I have a function that creates an instance of the class and returns the result of the method. My goal is to create a jest mock implementation of methodOne so that it concats the strings in reverse order (Hello, World) becomes WorldHello. Can anyone help me figure out how to create a mock to accomplish this? The goal is for the second test to pass and for the serviceFunction to return the mocked methods implemented return.

handler.ts:


class Service {
    constructor() {}

    methodOne(a, b) {
        return a + b
    }
}

const serviceFunction = (a, b) => {

    const obj = new Service()
    return obj.methodOne(a, b)

}

module.exports = { Service, serviceFunction }

handler.test.ts:

const myModule = require('./handler.ts')

describe('Test Suite One', () => {
    it('should concat Strings', () => {
        const service = new myModule.Service()

        const result = myModule.serviceFunction("Hello", "World")
        expect(result).toEqual("HelloWorld")
    })

    it('should mock methodOne to reverse concat strings', () => {
        const service = new myModule.Service()
        const result = myModule.serviceFunction("Hello", "World")
        expect(result).toEqual('WorldHello')
    })
})
about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!