Angular: 测试 - 预期 spy open 已被调用

Angular: Testing - Expected spy open to have been called

我正在为弹出模式编写测试。它抛出错误 Expected spy open to have been called 并且间谍 open 已经声明。我可以知道我错过了什么吗?

app.spec.ts

      it('should open modal', () => {
        const translation = {
          statusMessage: {
            popup: {
              badRequest: {
                title: 'Bad Request',
                message: 'Message..'
              }
            }
          }
        };
        spyOn(translate, 'getTranslation').and.returnValue(of(translation));
        spyOn(modalService, 'open').and.callThrough();

        const title = translate.get('title');
        const message = translate.get('message');

        component.showPopUp('title', 'message');
        fixture.detectChanges();
        expect(modalService.open).toHaveBeenCalled();
      });

app.ts

  showModal(title, message) {
    this.translate.getTranslation('en').subscribe((translations) => {
      this.modalService.open(
        title,
        message,
        {
          title: 'Go back',
          onClick: () => {
            return;
          }
        },
        true
      );
    });
  }

您正在测试异步代码我建议您使用 fakeAsync,试试这个

it('should work..', fakeAsync(() => {
   const translation = {
      statusMessage: {
        popup: {
          badRequest: {
            title: 'Bad Request',
            message: 'Message..'
          }
        }
      }
    };
    spyOn(translate, 'getTranslation').and.returnValue(of(translation));
    spyOn(modalService, 'open').and.callThrough();

    const title = translate.get('title');
    const message = translate.get('message');

    component.showPopUp('title', 'message');
    tick();
    fixture.detectChanges();
    expect(modalService.open).toHaveBeenCalled();
}));