Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何模拟其实例是使用new创建的类 导出类myMainClass{ 异步采样方法(req,res):承诺{ const result=wait new HelperClass().randomMethod() } }_Typescript_Mocking - Fatal编程技术网

Typescript 如何模拟其实例是使用new创建的类 导出类myMainClass{ 异步采样方法(req,res):承诺{ const result=wait new HelperClass().randomMethod() } }

Typescript 如何模拟其实例是使用new创建的类 导出类myMainClass{ 异步采样方法(req,res):承诺{ const result=wait new HelperClass().randomMethod() } },typescript,mocking,Typescript,Mocking,在为sampleMethod编写单元测试用例时,如何模拟helper类方法?由于您没有指定使用哪个测试包,下面是Jest解决方案 通过将模拟实现保存在mocks文件夹中,创建手动模拟。这允许您指定实现,并且它可以跨测试文件使用 export class myMainClass { async sampleMethod(req, res):Promise<any>{ const result = await new HelperClass().randomMe

在为sampleMethod编写单元测试用例时,如何模拟helper类方法?

由于您没有指定使用哪个测试包,下面是Jest解决方案

通过将模拟实现保存在mocks文件夹中,创建手动模拟。这允许您指定实现,并且它可以跨测试文件使用

export class myMainClass {

    async sampleMethod(req, res):Promise<any>{
        const result = await new HelperClass().randomMethod()
    }
}
导入所有实例共享的mock和mock方法:

// __mocks__/HelperClass.js

// Import this named export into your test file:
export const mockRandomMethod = jest.fn();
const mock = jest.fn().mockImplementation(() => {
  return {randomMethod: mockRandomMethod};
});

export default mock;

你好,梅德特,我已经尝试过上述解决方案,但对我无效。我正在使用jest框架进行单元测试
// myMainClass.test.js
import HelperClass, {mockRandomMethod} from './HelperClass';
import myMainClass from './myMainClass';
jest.mock('./HelperClass'); // HelperClass is now a mock constructor

beforeEach(() => {
  // Clear all instances and calls to constructor and all methods:
  HelperClass.mockClear();
  mockRandomMethod.mockClear();
});


it('We can check if the consumer called a method on the class instance', () => {
  const myMainClassInstance = new myMainClass();
  myMainClassInstance.sampleMethod();
  expect(mockRandomMethod).toHaveBeenCalled();
});