我有一个div,仅当当前路径是特定页面时才显示,否则将其隐藏所有其他时间,并且我正在为此编写Jasmine单元测试。
HTML标记:
<div class="header" *ngIf="router.url ='/home'">
茉莉花单元测试:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let el: DebugElement;
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
fixture.detectChanges();
});
it('should display div when on the home page', () => {
expect(el.query(By.css('.header')).nativeElement.style.visibility).toBe(true);
});
it('should hide div when not on home page', () => {
expect(el.query(By.css('.header')).nativeElement.style.visibility).toBe(false);
});
});
注意:应用加载路线时的第一页将是/ home。
谢谢!
答案 0 :(得分:1)
在每次测试时重新编写您的路由器URL值。因为它是只读属性,所以请考虑使用Object.defineProperty
:
it('should display div when on the home page', () => {
Object.defineProperty(component.router, 'url', { writable: true, value: '/home'});
expect(el.query(By.css('.header')).nativeElement.style.visibility).toBe(true);
});
it('should hide div when not on home page', () => {
Object.defineProperty(component.router, 'url', { writable: true, value: '/not-home'});
expect(el.query(By.css('.header')).nativeElement.style.visibility).toBe(false);
});