我正在试图监视已经通过Jest传递给异步函数的参数。
我非常简单的模块......
// data_loader.js
import axios from "axios";
export const data_loader = ( options ) => {
return axios( generateUrl( options ) )
.then( response => response.data );
};
和我的考试......
// data_loader.test.js
import * as data_loader from "./data_loader";
// this spies on the "load" function and passes
it("should be called once", () => {
const spy = data_loader.load = jest.fn();
data_loader.load(options);
expect(spy).toHaveBeenCalledTimes(1);
});
// here's where i'm trying to spy on axios to see if it is called with appropriate arguments
it("axios should be called with the supplied options", () => {
// have tried all syntax under the sun
});
如果我理解正确,我相信我需要嘲笑axios,因为没有理由需要真正调用它来检查它收到的论据。
我已经尝试了jest.mock("axios")
,jest.spyOn("axios")
和一些针对Axios的模拟库,但我无法理解语法。
答案 0 :(得分:2)
经过多次尝试后,我应该学会RTFM。
在调用data_loader.load函数之前,我使用axios-mock-adapter来模拟调用。我还修改了load函数以返回一个promise 。
然后,您可以通过回复来电来声明承诺的结果。这似乎是Jest知道等待的方式。
模块......
// data_loader.js
import axios from "axios";
export const load = (options) => {
return new Promise((resolve, reject) => {
axios(generateUrl(options))
.then(response => {
resolve(response);
})
.catch(err => {
reject(err);
});
});
};
和测试...
// data_loader.test.js
import axios from "axios"; // we need to import this so the mocking library can wrap it
import MockAdapter from "axios-mock-adapter";
const mock = new MockAdapter(axios); // wrap the real axios with the fake axios
it("axios should be called with the generated url", () => {
expect.assertions(1); // tell Jest that we're expecting one assertion
mock.onAny().reply(200, {}); // use the mock on any call to axios
return loader.load(...options).then(response => { // "return" is vital here - jest won't wait without it
expect(response.config.url)
.toBe("/my-generated-url");
});
});