【问题标题】:Jest - spy on nested promise (axios)Jest - 窥探嵌套的 Promise (axios)
【发布时间】:2018-08-25 18:52:53
【问题描述】:

我正在尝试使用 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 的模拟库,但我无法理解语法。

【问题讨论】:

    标签: javascript unit-testing axios jestjs


    【解决方案1】:

    所以经过大量尝试后,我应该学会了RTFM

    在调用 data_loader.load 函数之前,我使用axios-mock-adapter 模拟调用。我还修改了加载函数以返回一个承诺

    然后您可以通过返回您的电话来断言承诺的结果。这似乎就是 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");
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2017-02-27
      • 2020-02-24
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多