【问题标题】:How to mock an ES6 class that is a named export in Jest?如何在 Jest 中模拟一个命名导出的 ES6 类?
【发布时间】:2019-10-19 12:31:03
【问题描述】:

Jest 文档清楚地显示了当它是默认导出时如何manually mock an ES6 class。例如,这是一个默认导出的类:

class QueryService {
    query(queryText: string): Promise<any> {
        // ----- Query the API -----

        // ----- Return the result -----
        return Promise.resolve({
            data: {
                ticker: 'GOOG',
                name: 'Alphabet Company'
            }
        });
    }
}

export default QueryService;

它被嘲笑如下:

const mockQuery = jest.fn();
jest.mock('./QueryService', () => {
    return jest.fn().mockImplementation(() => {
        return {query: mockQuery};
    });
});

但是,如果它是一个命名导出,我该如何模拟这个类?我想不通!

这是我的full repo with this example

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    在这里回答:https://github.com/facebook/jest/issues/8532

    总结:

    const mockQuery = jest.fn();
    jest.mock('./QueryService', () => {
        return {
            QueryService: jest.fn().mockImplementation(() => {
                return { query: mockQuery };
            })
        };
    });
    

    【讨论】:

    • 我在该问题中找不到相同内容的手动模拟。您有任何手动模拟命名导出类的示例吗?
    【解决方案2】:

    对于您想要使用专为类设计的spyOn() 函数的类

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-09
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 2021-06-11
      相关资源
      最近更新 更多