无法监视另一个 class 中的 class 实例
Unable to spy on a class instance inside another class
我正在控制器 class 中实例化服务 class,控制器中使用了服务的 log
方法。
在 spec 文件中,我在 log 方法上添加了 spy,但是没有调用 spy。
这是我的代码
test.service.ts
export class TestService {
public log(msg: string): void {
console.log(msg);
}
}
test.controller.ts
import { TestService } from "../service/cart.service";
export class CartController {
private testService: TestService;
constructor() {
this.testService = new TestService();
}
public testFx():void {
this.testService.log("Here is a dummy msg.")
}
}
test.controller.spec.ts
import { TestController } from "./test.controller";
import { TestService } from "./test.service";
describe("Testing controller", () => {
private testController: TestController = new TestController();
private testService: TestService = new TestService();
it ("test function", () => {
spyOn(testService, "log");
testController.testFx();
expect(testService.log).toHaveBeenCalled();
});
})
错误:- Expected spy log to have been called.
而不是创建一个新的 class 实例,
private testController: TestController = new TestController();
private testService: TestService = new TestService();
it ("test function", () => {
spyOn(testService, "log");
你可以使用 escape hatch
。
试试这个:
private testController: TestController = new TestController();
it ("test function", () => {
spyOn(testController["testService"], "log");
由于 private, protected and public
是 typescript 语法糖的概念,因此当代码编译为 javascript 时它与它无关。
更具解释性的答案是 .
我正在控制器 class 中实例化服务 class,控制器中使用了服务的 log
方法。
在 spec 文件中,我在 log 方法上添加了 spy,但是没有调用 spy。
这是我的代码
test.service.ts
export class TestService {
public log(msg: string): void {
console.log(msg);
}
}
test.controller.ts
import { TestService } from "../service/cart.service";
export class CartController {
private testService: TestService;
constructor() {
this.testService = new TestService();
}
public testFx():void {
this.testService.log("Here is a dummy msg.")
}
}
test.controller.spec.ts
import { TestController } from "./test.controller";
import { TestService } from "./test.service";
describe("Testing controller", () => {
private testController: TestController = new TestController();
private testService: TestService = new TestService();
it ("test function", () => {
spyOn(testService, "log");
testController.testFx();
expect(testService.log).toHaveBeenCalled();
});
})
错误:- Expected spy log to have been called.
而不是创建一个新的 class 实例,
private testController: TestController = new TestController();
private testService: TestService = new TestService();
it ("test function", () => {
spyOn(testService, "log");
你可以使用 escape hatch
。
试试这个:
private testController: TestController = new TestController();
it ("test function", () => {
spyOn(testController["testService"], "log");
由于 private, protected and public
是 typescript 语法糖的概念,因此当代码编译为 javascript 时它与它无关。
更具解释性的答案是