Search code examples
node.jsjestjspact

Trying to spyOn a response inside a fire-and-forget method with jest


I'm working on a project in node.js where I'm setting up contract testing So I want to test my API requests and response here is the method I want to test

import rp from 'request-promise';
    
const foo = async () : Promise<void> => { 
      await rp(options).then(resp => {
        return resp;
      })
    }

here in my test I want to check the resp (which will be provided by the pact when running the test) The problem is I do not know how I can capture this variable to check it... I've tried to use spies with no success and a mock won't help...

import requestPromise from "request-promise";

const response = jest.spyOn(requestPromise(options),"then") 

await foo()

expect(response).toReturnWith({test:"test"})

I also tried to spyOn requestPromise() "post" but no results

Is there a way to test this ?


Solution

  • It's not clear what you're trying to attempt here. You mention Pact but there is no use of it in your example.

    Why do you need to spy on the request at all? Just return something from foo itself (instead of void) and assert on the response.

    If you're using Pact, it will do all of the http request checks for you. And ensure the request was made.

    You then just assert on the response.