angular - 使用 Jasmine 在路由和 routerLink 中进行角单元测试
问题描述
我是 Angular 和单元测试的新手。我创建了一个用于在 Angular 中测试路由的新项目。我按照Angular 官方文档中的指南进行操作。它在测试 routerLink 时确实有效。
但这是一个问题。我忘记在 app.routing.module.ts 中创建路由,但测试仍然通过。
这是 routing.module.ts 中的代码
const routes: Routes = [];
并在 html
<a routerLink="/order">Order</a><br/>
<a routerLink="/creditCard">Credit Card</a>
在spec.ts
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let app: any;
let compiled: any;
let linkDes:any;
let routerLinks:any;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent,
RouterLinkDirectiveStub
]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(AppComponent);
app = fixture.debugElement.componentInstance;
fixture.detectChanges();
compiled = fixture.debugElement.nativeElement;
// find DebugElements with an attached RouterLinkStubDirective
linkDes = fixture.debugElement
.queryAll(By.directive(RouterLinkDirectiveStub));
// get attached link directive instances
// using each DebugElement's injector
routerLinks = linkDes.map(de => de.injector.get(RouterLinkDirectiveStub));
})
}));
it('should create the app', () => {
expect(app).toBeTruthy();
});
it(`should have as title 'unitTesting'`, () => {
expect(app.title).toEqual('unitTesting');
});
it('should render title in a h1 tag', () => {
expect(compiled.querySelector('h1').textContent).toContain('Welcome to unitTesting!');
});
it('can get RouterLinks from page', () => {
expect(routerLinks.length).toBe(2, 'should have 2 routerLinks');
expect(routerLinks[0].linkParams).toBe('/order');
expect(routerLinks[1].linkParams).toBe('/creditCard');
});
});
我理解单元测试应该被隔离。但在某些情况下,它应该有连接才能进行测试。
我用谷歌搜索。但是很多答案只是与静态路径进行比较。
我的问题是,如何在如下场景中进行测试:
在路由.module.ts
常量路线:路线= [
{path:"order",component:OrderComponent}, {path:"creditCard",component:CreditcardComponent}
];
2.在两个或多个页面中具有相同的锚标签
<a routerLink="/order">Order</a><br/>
<a routerLink="/creditCard">Credit Card</a>
3.如果有人改变了routing.module.ts中的路径,比如
{path:"orderDetail",component:OrderComponent},
并且忘记在所有或一个 html 文件中更改 routerLink 的路径,对于那些忘记更改 routerLink 路径的组件,测试用例仍将通过。
因此,如何修复它以在测试用例中显示失败。
解决方案
推荐阅读
- c++ - 当向量的两个元素相乘时,向量c ++与运算符*不匹配
- c# - 公开 razor 视图的依赖注入以进行测试
- java - janino 编译 Java 代码抛出“找不到类异常”
- c - 为什么 timerfd 定期 Linux 定时器的到期时间比预期的要早一点?
- angular - Ng-bootstrap 模式窗口在订阅的错误部分不起作用
- html - 是否可以使用重复线性渐变属性设置边框图像和背景?
- javascript - 将 .css 文件中的 CSS 添加到材质组件
- wordpress - 在产品画廊阵容中 - 使简短的摘录成为最小长度
- apache-spark - Exception while starting Spark History Server
- google-chrome - 如何在 cypress 中为 chrome 浏览器设置代理