我可以将 jest.fn() 相关检查与 axios-mock-adapter 一起使用吗?



我正在使用axios-mock-adapter,我想知道我是否可以设置它,以便我也可以做出类似expect(MockAdapter.get).toHaveBeenCalledWith(url);

我尝试了以下方法:

// 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;
}

它说

    expect(jest.fn())[.not].toHaveBeenCalledWith()
    Matcher error: received value must be a mock or spy function
    Received has value: undefined

如果我添加一个./__mocks__/axios.js文件,我会立即得到

    TypeError: axios.create is not a function
    > 1 | import MockAdapter from "axios-mock-adapter";
        | ^
      2 | import { fetchProducts } from "../src/redux/actions/productActions";

有没有办法做到这一点,或者它要么模拟我自己的axios函数实现,要么在没有访问权限的情况下使用它axios-mock-adapter作为开玩笑的模拟函数?

你需要像这样创建一个间谍:

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();

最新更新