【问题标题】:Angular - spy not recognising function being calledAngular - 间谍无法识别被调用的函数
【发布时间】:2018-01-31 16:18:12
【问题描述】:

我正在尝试测试我的一个功能模块,但我遇到了困难。我的最后一次测试失败了,因为间谍不认为该方法被调用。即使我将this.translate.use(this.currentLanguage.i18n) 调用移到订阅块之外。

这是特征组件:

export class LanguagesComponent implements OnDestroy, OnInit {

  public languages = [
    {
      id: '0',
      name: this.translate.stream('LANGUAGES.SWEDISH'),
      i18n: 'sv',
      flag: {
        src: './assets/img/sv.svg'
      }
    },
    {
      id: '1',
      name: this.translate.stream('LANGUAGES.ENGLISH'),
      i18n: 'en',
      flag: {
        src: './assets/img/en.svg'
      }
    }
  ];

  public currentLanguage: any;

  private storageSubscription: Subscription;

  constructor(
    private cs: ClientStorage,
    private notifications: NotificationsApi,
    private router: Router,
    private translate: TranslateService
  ) {}

  ngOnInit() {

    const storedLanguage: any = this.cs.getItem(AppConstants.currentLanguage);

    this.currentLanguage = FindObjectByQuery(this.languages, 'i18n', storedLanguage);

    // Listen for when the language changes from other places than this component
    this.storageSubscription = this.cs.logger$
      .filter(data => data && data.key === AppConstants.currentLanguage)
      .subscribe((currentLanguage: any) => {

        if (currentLanguage) {

          this.currentLanguage = FindObjectByQuery(this.languages, 'i18n', currentLanguage.value);

          // Set the current language to use
          this.translate.use(this.currentLanguage.i18n);
        }
      }
    );
  }

  ngOnDestroy() {
    this.storageSubscription.unsubscribe();
  }

  selectLanguage(language: any): void {

    this.cs.setItem(AppConstants.currentLanguage, language.i18n);

    this.router.navigate(['dashboard']);

    this.notifications.newNotification({message: this.translate.instant('NOTIFICATIONS.LANGUAGES.CHANGED'), theme: 'success'});
  }
}

到目前为止,这些是我的测试:

describe('[UNIT] LanguagesComponent', () => {

  let component: LanguagesComponent;
  let fixture: ComponentFixture<LanguagesComponent>;
  let translate: Location;

  beforeEach(() => {

    TestBed.configureTestingModule({
      imports: [
        ModuleImports
      ],
      providers: [
        TranslateService
      ],
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [LanguagesComponent, DummyComponent]
    });

    fixture = TestBed.createComponent(LanguagesComponent);
    component = fixture.componentInstance;
    translate = TestBed.get(TranslateService);

    // Make sure ngOnInit runs
    fixture.detectChanges();
  });

  it('should create the component', async(() => {
    expect(component).toBeTruthy();
  }));

  it('should have a current language when the component has loaded', () => {
    expect(component.currentLanguage).toBeTruthy();
  });

  it('should have the needed properties in the current language', () => {

    const currentLanguage = component.currentLanguage;

    expect(currentLanguage.id).toBeTruthy();
    expect(currentLanguage.name).toBeTruthy();
    expect(currentLanguage.i18n).toBeTruthy();
    expect(currentLanguage.flag.src).toBeTruthy();
  });

  it('should call the use method of TranslateService with the current language i18n property', () => {

    const spy = spyOn(translate, 'use').and.callThrough();

    expect(spy).toHaveBeenCalledWith(component.currentLanguage.i18n);
  });
});

【问题讨论】:

    标签: angular unit-testing typescript karma-jasmine


    【解决方案1】:

    在您的测试中,您创建了一个间谍,然后您立即尝试验证呼叫。但是没有电话。

    对此有两种可能的解决方案。

    1. spyOn 移动到fixture.detect 更改之前beforeEach
    2. 创建间谍后,调用/触发将/应该触发预期调用的适当方法。在这种情况下,需要调用 fixture.detectChanges

    注意:我没有针对任何其他问题运行您的测试,但基本问题是间谍创建和间谍使用之间缺少调用。

    【讨论】:

    • 谢谢!在我的同步 beforeEach() 块内我的间谍声明之后,我移动了我的 fixture.detectChanges(),它现在按预期工作。
    猜你喜欢
    • 2018-01-07
    • 2015-11-22
    • 2023-03-20
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    相关资源
    最近更新 更多