【问题标题】:Test typescript async function using Jest使用 Jest 测试 typescript 异步函数
【发布时间】:2019-02-20 16:24:46
【问题描述】:

我在主打字稿文件中有以下代码:

public readonly funcname = async (param: string): Promise<CustomeType> => {
    const constname = somefunction(strparam, jsonparam);
    return Promise.resolve({
        reqname:constname
    });
};

这是在一个导出类下编写的,比如exportedservice。

我正在开玩笑地编写以下测试用例:

const outputMock = jest.fn(() => {
    return Promise.reject();
});

const exportedserviceobj = new exportedservice();

describe('Statement', () => {
    it('statement', async () => {
        expect.assertions(1);
        const outputResult = await exportedserviceobj.funcname('TestFile');
        outputMock().then(outputResult);
        expect(outputResult).toEqual('undefined');
    });
});

在运行测试用例时;它抛出一个类型错误:

exportedservice.funcname is not a function

因为我是打字稿的新手;所以经过大量的研发;我无法解决问题。请提出适当的方法来解决这个问题。提前致谢。

【问题讨论】:

  • exportedservice 已定义?如果是这样,您是否在测试中查看过它们的结构?

标签: typescript testing jestjs


【解决方案1】:

你必须模拟exportedservice。例如:

import * as Exportedservice from './exportedservice'
jest.mock('./exportedservice')
describe('Statement', () => {
it('statement', async () => {
    Exportedserviceobj.funcname = jest.fn().mockResolvedValue('test');
    const outputResult = await Exportedserviceobj.funcname('TestFile');
    expect(outputResult).toEqual('test');
});

});

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2019-03-04
    • 1970-01-01
    • 2018-11-21
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    相关资源
    最近更新 更多