2

I'm using axios-mock-adapter and I want to know if I can set it up so that I can also make assertions like expect(MockAdapter.get).toHaveBeenCalledWith(url);

I've tried the following:

// test
import MockAdapter from "axios-mock-adapter";
import { fetchProducts } from "../src/redux/actions/productActions";

describe("fetchProducts", () => {
  const mock = new MockAdapter();
  it("fetches the products", async () => {
    const x = await fetchProducts();
    expect(mock.get).toHaveBeenCalledWith("https://www.whatever.com");
  });
});

// function
import axios from "axios";

export async function* fetchProducts() {
  let data = await axios.get("https://www.whatever.com");
  return data;
}

And it says

    expect(jest.fn())[.not].toHaveBeenCalledWith()

    Matcher error: received value must be a mock or spy function

    Received has value: undefined

If I add a ./__mocks__/axios.js file, I immediately get

    TypeError: axios.create is not a function

    > 1 | import MockAdapter from "axios-mock-adapter";
        | ^
      2 | import { fetchProducts } from "../src/redux/actions/productActions";

Is there a way to do this, or is it either mock my own implementation of axios functions, or use axios-mock-adapter without access to it as a jest mock function?

Jonathan Tuzman
  • 11,568
  • 18
  • 69
  • 129

1 Answers1

1

You need to create a spy like so:

const spy = jest.spyOn(mock, 'onGet');

mock.onGet('https://www.whatever.com').reply(200);

// only if mock client has been called with https://www.whatever.com the test will pass
expect(spy).toHaveBeenCalled();