javascript - Jest - 监视嵌套的 promise (axios)

标签 javascript unit-testing axios jestjs

我正在尝试使用 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/

相关文章:

javascript - 在网页上使用openstreetmap

javascript - jquery 找不到文本

javascript - Ember 单元测试渲染 Handlebars 返回 null 或 undefined

reactjs - 刷新 Promise 队列?

reactjs - 类型错误 : Cannot read property 'get' of undefined with useEffect and Axios

javascript - jQuery 没有响应第一段隐藏

java - 单元测试覆盖调用 super() 的方法

unit-testing - Cognos 上的自动化单元测试是否可行?

javascript - Axios post 为对象添加额外的键

javascript - Pager.js : How to lazy load bindings