gpt4 book ai didi

unit-testing - 如何在 Angular2 中使用 karma-jasmine 对 ng2-translate 进行单元测试

转载 作者:太空狗 更新时间:2023-10-29 17:21:07 25 4
gpt4 key购买 nike

我正在尝试使用 ng2-translate 翻译带有德语和英语选项的页面。

navbar.component.html

<div id="sidebar-wrapper">
    <div class="side-wrap-div">
        <div class="list-group sidebar-nav">
            <li class="list-group-item borderBottomMenu active" >
                <a href="#">{{ 'PAGE.GENERAL' | translate}}</a>
                <span class="marker-logo"></span>
                <span class="logo allgemein-logo-click" ></span>
            </li>
        </div>
    </div>
</div>

navbar.component.spec.ts

import { TestBed, ComponentFixture, async } from "@angular/core/testing";
import { DebugElement } from "@angular/core";
import { By } from "@angular/platform-browser";
import { SidenavComponent } from "../sidenav/sidenav.component";
import {TranslateService, TranslateModule} from "ng2-translate";


class TranslateServiceMock {
    private lang: string;
    public getTranslation() : string {
        return this.lang;
    }
}
describe('Navbar Component Test', () => {

    let comp: SidenavComponent;
    let fixture: ComponentFixture<SidenavComponent>;
    
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ SidenavComponent ], // declare the test component

            providers: [ {provide: TranslateService, useClass: TranslateServiceMock} ]
        })
            .compileComponents();
        fixture = TestBed.createComponent(SidenavComponent);

        comp = fixture.componentInstance;

    }));

it('should have a taskview header', () => {
        fixture.detectChanges();

        expect("How to test the getTranslation() here????" ).toContain('General');


    })
});

翻译正在进行中,{{ 'PAGE.GENERAL' | translate}} 被正确翻译。因此在规范中,TranslateService 的 getTranslation() 是从 Json 文件(en.json 和 de.json)中获取数据。我在 TranslateServiceMock 中模拟这个服务。我如何测试这个?有帮助吗?

最佳答案

您正在测试 NavbarComponent,而不是翻译服务。所以你想要的是检查导航栏链接的内容,而不是服务的响应。

import { By } from '@angular/platform-browser'; 
// ...

// By.css: this example or some selection that gets the element you want
const element = fixture.debugElement.query(By.css('.list-group-item > a'));

// note: you should use ".toEqual('General')" if you want an exact match.
expect(element.nativeElement.textContent).toContain('General');

但是,如果您需要获取服务实例的句柄:

const translateService = fixture.debugElement.injector.get(TranslateService);

您可以找到所有 this documented here.

关于unit-testing - 如何在 Angular2 中使用 karma-jasmine 对 ng2-translate 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41183170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com