使用开玩笑的Test TypeScript异步函数



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

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

这是在出口级别的Say 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

我是TypeScript的新手;因此,经过大量研发;我无法解决问题。请提出适当的解决方法。提前致谢。

您必须模拟导出服务。例如:

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');
});

});

最新更新