首页 > 解决方案 > 如何使用 TranslateService 对组件进行单元测试

问题描述

我非常仔细地遵循了这一点: Git issue #636

但我无法解决我的问题。让我解释。我有一个TimeSelector组件,我已经将文件中的所有字符串都外部化了i18n/en-US.json。最初,当页面加载时,我recievedFromChild使用CY 2020 VS CY 2019. 我存储CY在哪里。因此,当页面加载时,我正在调用. 我只是想测试这个东西。这是代码:VSen-US.jsontranslate.get([...]).subscribe(...)

timeselector.component.html

<div>{{recievedFromChild}}</div>

timeselector.component.ts

import { Component, OnInit, ... } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
...

@Component({
    selector: 'app-timeselector',
    templateUrl: './timeselector.component.html'
})
export class TimeselectorComponent implements OnInit, AfterViewInit {

    calendarYearLabel: string;
    versusLabel: string;

    date = new Date();
    currentYear = this.date.getFullYear();
    previousYear= (this.date.getFullYear())-1;

    recievedFromChild; // <=========================== THIS I WANT TO TEST

    constructor(private translate: TranslateService,...) {}

    ngOnInit(): void {
      this.translateModes();
    }

    translateModes(): void {
      this.translate
        .get([
            'Timeselection.Abbreviations.CalendarYear',
            'Timeselection.Abbreviations.Versus'
        ])
        .subscribe(translations => {
          this.calendarYearLabel=translations['Timeselection.Abbreviations.CalendarYear'];
          this.versusLabel = translations['Timeselection.Abbreviations.Versus'];
          this.recievedFromChild =
              this.calendarYearLabel +
              ' ' +
              this.currentYear +
              ' ' +
              this.versusLabel +
              ' ' +
              this.calendarYearLabel +
              ' ' +
              this.previousYear;
        });
    }    
}

这是外部文件:en-US.json

"Timeselection": {
    "Abbreviations": {
      "CalendarYear": "CY",   
      "Versus": "VS"
    }
}

这是我的测试文件:timeselector.component.spec.ts

import { TestBed, ComponentFixture, async } from "@angular/core/testing"
import { TimeselectorComponent } from './timeselector.component'
...
import { TranslateService } from '@ngx-translate/core';
...

fdescribe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    let mockTranslateService;

    beforeEach(async(()=>{
        mockTranslateService = jasmine.createSpyObj(['get']);

        TestBed.configureTestingModule({
            providers: [
                {provide: TranslateService, useValue: mockTranslateService},
                ...
            ],
            declarations: [
                ...
            ]
        });
        fixture = TestBed.createComponent(TimeselectorComponent);

    }))

    it('should create', ()=> {
        expect(fixture.componentInstance).toBeTruthy();
    })

    // THIS IS THE TEST CASE    
    it('should initially display current and previous calendar years only', () => {
        //fixture.componentInstance.translateModes();
        //fixture.detectChanges(); 
        expect(fixture.componentInstance.recievedFromChild).toBe('CY 2020 VS CY 2019');
    })
})

但我得到了这个失败的测试用例:

类型错误:this.translate.get(...) 未定义

下面是测试用例的截图:

在此处输入图像描述

请告诉我现在该怎么做。我被封锁了。

标签: angularkarma-jasmineangular-unit-test

解决方案


推荐阅读