jeudi 21 février 2019

How to determine if a nested function has been called with jest.fn()?

I have a handy set of apiHelpers. One of the functions is a wrapper around axios's get method called getWrapper

const getWrapper = (url) => (
  (endpoint, headers={}) => (
    axios.get(
      `${url}${endpoint}`,
      {headers: { ...getHeaders(), ...headers }}       
    )
  )
);

For unauthenticated calls, I have a getUnauthenticatedApiHelper function that calls getWrapper. getWrapper does a few things, one of which is concatenating the supplied endpoint to BASE_URL which is an env variable.

export const getUnauthenticatedApiHelper = (endpoint, headers) => getWrapper(BASE_URL)(endpoint, headers);

My test calls getUnauthenticatedApiHelper and expects that it then calls getWrapper.

describe('apihelpers', () => {
  test('getUnauth', () => {
    const getWrapper = jest.fn();
    var wtf = getUnauthenticatedHelper('end/point/');
    console.log(wtf);
    expect(getWrapper).toHaveBeenCalled();
  });
});

When I log out the result, I can see that the endpoint has correctly been concatenated with BASE_URL, however my test fails with the error Expected mock function to have been called, but it was not called.

Whether or not this is a valid thing to be testing or not is beside the point atm because I'm just trying to get my head around how to effectively use jest. I have been experimenting with this in an online repl here - and no matter what I do, I keep running into the problem of getWrapper not being called which makes me believe that there’s something fundamental I'm misunderstanding about jest.fn() - so what am I missing and how should I be testing that getWrapper is called?

Aucun commentaire:

Enregistrer un commentaire