如何使用Jasmine在Angular中测试路线的存在? [英] How to test the existence of a route in Angular using Jasmine?
问题描述
我正在尝试编写一个测试,使用Jasmine for Angular应用程序检查路由的存在:
I'm trying to write a test that checks for the existence of a route using Jasmine for Angular application:
import { routes } from './app-routing.module';
import { UsersComponent } from './users/users.component';
describe('routes', () => {
it('should contain route for /users', () => {
const expectedRoute = { path: 'users', component: UsersComponent };
expect(routes).toContain(expectedRoute);
});
});
,但是测试失败(可能是由于Java语言对象相等如何)中的对象相等检查Javascript中的工作?)
but the test fails (probably because of object equality in Javascript How object equality checks work in Javascript?)
如何修改测试以使其正常工作?
How to modify the test to make it work?
推荐答案
我已经尝试过了,它可以很好地与您的代码配合使用.
I have tried it, and it works fine with your code.
方法toContain
的相等性没有问题.
There's no problem with equality in the method toContain
.
您在app-routing.module.ts
中将const routes
更改为export const routes
,并且在测试中将import { routes } from './app-routing.module'
更改了吗?
Have you changed const routes
to export const routes
in your app-routing.module.ts
, and import { routes } from './app-routing.module'
in your test?
这是我为了测试应用程序而必须更改的唯一内容.
It's the only thing that I had to change in order to test the app.
我已完成以下步骤:
-
ng new test-routing
(对路由说是,因此创建了app-routing.module.ts
. - 用以下代码修改了
app.component.spec.ts
:
ng new test-routing
(saying yes to routing so theapp-routing.module.ts
is created.- Modified
app.component.spec.ts
with the following code:
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { routes } from './app-routing.module';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should contain route for /principal', () => {
const expectedRoute = { path: 'principal', component: AppComponent };
expect(routes).toContain(expectedRoute);
});
});
- 修改了
app-routing.module.ts
以添加以下路线: - Modified the
app-routing.module.ts
to add this routes:
export const routes: Routes = [
{ path: '', redirectTo: '/principal', pathMatch: 'full' },
{ path: 'principal', component: AppComponent }
];
- 运行
ng test
- Run
ng test
测试很好.
如果将'principal'
路径更改为其他路径,则测试将失败.
如果我恢复到良好状态,则测试可以正常进行.
If I change the 'principal'
path to other, the test fails.
If I revert to the good one, the test goes ok.
这篇关于如何使用Jasmine在Angular中测试路线的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!