angular - 如何使用 TranslateService 对组件进行单元测试
问题描述
我非常仔细地遵循了这一点: Git issue #636。
但我无法解决我的问题。让我解释。我有一个TimeSelector
组件,我已经将文件中的所有字符串都外部化了i18n/en-US.json
。最初,当页面加载时,我recievedFromChild
使用CY 2020 VS CY 2019
. 我存储CY
在哪里。因此,当页面加载时,我正在调用. 我只是想测试这个东西。这是代码:VS
en-US.json
translate.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(...) 未定义
下面是测试用例的截图:
请告诉我现在该怎么做。我被封锁了。
解决方案
推荐阅读
- javascript - 节点 WPAPI 媒体无法上传“rest_upload_no_data”
- arduino - 调用其他 void 函数后 Arduino/Teensy 主循环未执行
- r - 根据分组属性添加新列
- c++ - 如何通过平均法线算法平滑网格表面?
- php - 使用php bindParam时:name中的冒号是什么意思
- ruby-on-rails - Ruby Rake 无重复数组选择任务
- java - Java从与其所在类相同的类的变量中获取数据
- c# - 如果选择了新的加电装置,如何禁用其他加电装置的效果?
- sql - 如何捕获每个索引的唯一约束错误?
- java - protobuf 反序列化时内存不足