【发布时间】:2021-08-05 12:40:10
【问题描述】:
我正在尝试测试 test.controller.ts 类中的一个方法,该方法也恰好调用了另一个正在单独测试的类中的方法,所以我想模拟该调用。
这是一个示例设置,以显示我正在尝试做的事情。
TestController.test.ts
import {TestController} from "../../src/controllers/test.controller";
import {TestService} from "../../src/services/test.service";
describe("Test TestController", () => {
test("exampleController", () => {
jest.mock('../../src/services/test.service');
let testService = new TestService();
let testController = new TestController();
// Mock testService.exampleService so it returns 2.
let result = testController.exampleController();
expect(result).resolves.toBe(2);
});
});
test.controller.ts
import {TestService} from "../services/test.service";
export class TestController {
private testService: TestService;
constructor() {
this.testService = new TestService();
}
public async exampleController() {
return await this.testService.exampleService();
}
}
test.service.ts
export class TestService {
public async exampleService() {
return 1;
}
}
如何模拟“exampleService”方法,以便从 test.controller.ts 对“exampleController”方法的调用使用此模拟版本?
【问题讨论】:
标签: javascript node.js typescript jestjs ts-jest