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

149
Views
How to mock a const with jest?

I've been getting an error while trying to unit test a new method on my service that returns an object that looks like this:

    { 
     requestHeaders: [
      {
        'header1': '...',
        'header2': '...',
        'header3': '...'
      },
      {
        'header1': '...',
        'header2': '...',
        'header3': '...'
    },
    {
        'header1': '...',
        'header2': '...',
        'header3': '...'
    },
   ]
  }

My service method:

    const requestObject = this.otherService.getRequestObject(payload);
    const [request] = requestObject.headers.attribute; // This doesn't look good

    if(request){
    // Do stuff
    }

When I run npm run test


    TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

      32 |     );
    > 33 |     const [request] = requestObject.headers.attribute;
         |                           ^

My breaking test:


  it('should call sendNewRequest() ', async () => {

    jest
      .spyOn(myService, 'isExistingRequest')
      .mockImplementation(() => Promise.resolve(false));

    jest
      .spyOn(myService, 'createNewRequest')
      .mockImplementation();

    await myService.handleRequest({});
    expect(myService.createNewProductionOrder).toHaveBeenCalled();
  });
});

I think that my getRequestObject is returning undefined because I'm sending an empty object to my handleRequest method, and getRequestObject is expecting a different thing. Now, have in mind that the object I exemplified here is not exactly as the original object is (the original one is much larger and have hundreds of fields), but it is an object with an array of objects.

How should I approach this since I want to avoid creating manually a requestObject inside my testing file?

It is worth mentioning that my getRequestObject method is declared like this in an utils file:

export const objectDtoTransformer = (params) => {doStuff}
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!