我正在尝试使用 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 模拟库,但我不能不明白语法。
最佳答案
所以经过大量尝试我应该学会了 RTFM .
我用了axios-mock-adapter在调用 data_loader.load 函数之前模拟调用。我还修改了加载函数以返回 promise 。
然后您可以通过返回您的电话 断言 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");
});
});
关于javascript - Jest - 监视嵌套的 promise (axios),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49325248/