samedi 15 février 2020

Using jest and puppeteer to test if xhr callback is called

I have a get function that wraps an xhr request, which includes a success callback. I'm trying to build a test that checks whether the success callback was called.

Here's the get function:

get: function(onSuccess, onFail){
   var xhr = new XMLHttpRequest();
   // ... open and send the request ... etc... 
   if(xhr.status === 200) {
      onSuccess(xhr.reponse);
   }

The get function is available in the window scope. I am able to run the following code in the browser on the page and observe the success callback running:

get(function(){console.log('success callback running')})

So far, I'm trying a test like this:

  it('runs the success handler when passing a success callback to get method', async () => {
    const mockCallback = jest.fn(() => "success");
    await page.evaluate((mockCallback) => {
      window.get(mockCallback);
    }, mockCallback);
    await expect(mockCallback).toHaveBeenCalled();
  });

This test is always failing saying that the number of calls to mockCallBack is less than 1.

Also of interest, if I change the get function to immediately execute the success callback, then I see an error that 'onSuccess' is not a function.

ie..

get: function(onSuccess, onFail){
    onSuccess();
    // etc..
}

Aucun commentaire:

Enregistrer un commentaire