首页 > 解决方案 > 如何使用茉莉花测试翻译服务中的字段标签

问题描述

我是使用 jasmine 对角度代码进行单元测试的新手。我正在尝试测试从 HTML 文件中的翻译服务获得的字段标签。我使用了以下代码,但出现错误“失败:无法读取 null 的属性‘textContent’”

it('label should be Enter your mobile number', async(() => {
     const de = fixture.debugElement;
     expect(fixture.debugElement.nativeElement.querySelector('[id=textFormat] label').textContent).toEqual('ENTER_YOUR_MOBILE_NUMBER'); 
     translate.setTranslation('en', { ENTER_YOUR_MOBILE_NUMBER : 'Enter your mobile number' });
    translate.use('en');
    fixture.detectChanges();
    expect(fixture.debugElement.nativeElement.querySelector('[id=textFormat] label').textContent).toEqual('Enter your mobile number'); 
       }));


HTML :

<div class="form-group" id="email">
        <label for="mobileNumber" class="col-form-label col-form-label-lg" id="textFormat">
            {{ 'ENTER_YOUR_MOBILE_NUMBER' | translate }}&nbsp;<span class="labelHint" id="numbFormat">(05XXXXXXXX)</span>
        </label>
       
    </div>

标签: jasminengx-translate

解决方案


我认为你的 CSS 选择器不准确,试试这个:

it('label should be Enter your mobile number', async(() => {
     const de = fixture.debugElement;
     expect(fixture.debugElement.nativeElement.querySelector('label#textFormat').textContent).toEqual('ENTER_YOUR_MOBILE_NUMBER'); 
     translate.setTranslation('en', { ENTER_YOUR_MOBILE_NUMBER : 'Enter your mobile number' });
    translate.use('en');
    fixture.detectChanges();
    expect(fixture.debugElement.nativeElement.querySelector('label#textForma').textContent).toEqual('Enter your mobile number'); 
       }));

更改querySelector.


推荐阅读