简体   繁体   English

使用Jest测试打字稿异步功能

[英]Test typescript async function using Jest

I have the following code in main typescript file: 我在主要打字稿文件中有以下代码:

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

This is written under an exported class say exportedservice. 这是在一个名为exportedservice的导出类下编写的。

I am writing the following testcase in jest for same: 我在开玩笑地编写以下测试用例:

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

while running the test case; 在运行测试用例时; it is throwing a type error: 它抛出类型错误:

exportedservice.funcname is not a function

As I am new to typescript; 我刚接触打字稿; so after a lot of R&D; 经过大量的研发 I am unable to resolve the issue. 我无法解决问题。 Please suggest appropriate way to solve this out. 请提出解决此问题的适当方法。 Thanks in Advance. 提前致谢。

You have to mock exportedservice. 您必须模拟exportedservice。 For example: 例如:

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

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM