【问题标题】:How i can spy constructor functions calls in my angular test?我如何在我的角度测试中监视构造函数调用?
【发布时间】:2020-11-11 02:44:44
【问题描述】:

我在constructor() 中有一项服务进行订阅并调用函数:

constructor(private router: Router) {
    this.router.events.subscribe((e) => {
      if (e instanceof RouterEvent) {
        this.closeModal();
      }
});
  

在我的测试中我尝试过:

describe('ModalService', () => {
   let service: ModalService;
   beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [
        {
          provide: Router,
          useClass: routeStub,
        },
      ],
    });
    router = TestBed.get(Router);
    service = TestBed.get(ModalService);

  fit('should close modal when is a instance of RouterEvent', async () => {
    spyOn(service, 'closeModal');
    await router.navigate(['/']);
    expect(service.closeModal).toHaveBeenCalled();
  });

})

我的路由器存根:

export const routeStub = (): Partial<Router> => {
  const events = of(new RouterEvent(1, 'test'));
  return {
    events,
    navigate: (commands: any[], extras?: NavigationExtras) => {
      return new Promise<boolean>((resolve, reject) => resolve(true));
    },
  };
};

当我在我的closeModal() 中添加一个console.log('test') 时,我的消息test 正在打印,但我的期望离开返回错误消息:

预期的间谍 closeModal 已被调用。

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    问题

    constructor 方法是在创建组件时调用的,所以当你测试它的时候,它已经被执行了。这就是测试失败但控制台日志显示该方法被调用的原因

    解决方案

    你需要监视类组件prototype实例

    fit('should close modal when is a instance of RouterEvent', async () => {
        
        const closeModalSpy = spyOn(AppComponent.prototype, 'closeModal').and.callThrough()
        TestBed.createComponent(AppComponent);
        expect(closeModalSpy).toHaveBeenCalled()
    
      });
    

    我已经测试了上述内容并且它有效

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多