我正在为测试路线编写单元测试,我有一个带登录按钮的登录页面,我想测试点击我的登录按钮页面应该导航到仪表板页面,但我不知道怎么做
这里有几行代码
import {
provide, DirectiveResolver, ViewResolver
}
from 'angular2/core';
import {
describe, expect, it, xit, inject, beforeEachProviders, beforeEach, injectAsync, TestComponentBuilder, setBaseTestProviders
}
from 'angular2/testing';
import {
TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS
}
from 'angular2/platform/testing/browser';
import {
Router, RouterOutlet, RouterLink, RouteParams, RouteData, Location, ROUTER_PRIMARY_COMPONENT
}
from 'angular2/router';
import {
RootRouter
}
from 'angular2/src/router/router';
import {
RouteRegistry
}
from 'angular2/src/router/route_registry';
import {
SpyLocation
}
from 'angular2/src/mock/location_mock';
import {
LoginComponent
}
from '../js/login.component';
import {
EnterpriseSearchComponent
}
from '../js/enterprise-search.component';
import {
AppConfig
}
from '../js/services/appconfig';
describe('login component', () => {
var location, router;
beforeEachProviders(() => {
return [
TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS,
provide(ROUTER_PRIMARY_COMPONENT, {
useValue: EnterpriseSearchComponent
}),
provide(Router, {
useClass: RootRouter
}), RouteRegistry,
provide(Location, {
useClass: SpyLocation
}), AppConfig
]
});
beforeEach(inject([Router, Location], (r, l) => {
router = r;
location = l;
}));
it('Should be able to navigate to Login page', (done) => {
router.navigate(['Login']).then(() => {
expect(location.path()).toBe('/login');
done();
}).catch(e => done.fail(e));
});
it('should validate login', injectAsync([TestComponentBuilder], (tcb) => {
return tcb.createAsync(LoginComponent).then((fixture) => {
fixture.detectChanges();
let compiled = fixture.debugElement.nativeElement;
let instance = fixture.componentInstance;
compiled.querySelector("#userid").value = 'dummyid';
compiled.querySelector("#passwrd").value = 'dummypassword';
fixture.detectChanges();
compiled = fixture.debugElement.nativeElement;
instance = fixture.componentInstance;
compiled.querySelector("#loginbtn").click();
fixture.detectChanges();
// here is where i want to test that the page is navigated to dashboard screen
});
}));
});
在上面的代码示例中,我想在上一个测试规范中测试导航
答案 0 :(得分:0)
const element = fixture.nativeElement;
fixture.detectChanges();
expect(element.querySelectorAll('.dashboard-title')).toBe('Dashboard');
或者我认为更干净的方式是
首先将你的灯具放入一个字段,即
return tcb.createAsync(LoginComponent).then((fixture) => {
this.myFixture = fixture;
...
然后你可以在不同的“案例”中验证它,如果该页面包含只有你的仪表板页面的特定元素
it('is this the login page?', () => {
const element = this.myFixture.nativeElement;
this.myFixture.detectChanges();
expect(element.querySelectorAll('.dashboard-title')).toBe('Dashboard');
});