LoginSignup
8
6

More than 5 years have passed since last update.

[Angular] テストレシピ - ルートパラメータを渡す

Last updated at Posted at 2019-01-08

これはなに?

Angularでは、URL中に含んだパラメータをコンポーネントで受け取ることができます。

例えば http://example.com/products/cat/100/id/10020 というURLから、cat=100、id=10020のようなパラメータを受け取ることができます。

そのようなコンポーネントに対して、テスト時にパラメータを渡す方法です。

テスト対象

以下のようなルーティングを設定していたとします。

app-routing.module.ts
// (省略)
const routes: Routes = [
  {
    path: 'detail/:id',
    component: DetailComponent,
    data: { animationState: 'detailPage' }
  }
];
// (省略)

コンポーネントで、以下のようにパラメータを受け取っていました。

detail.component.ts
// (省略)
@Component()
export class DetailComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    // 文字列なので、数値に変換しています。
    const id = parseInt(this.route.snapshot.paramMap.get('id'), 10);
  }
}

テストコード

テストコードはこのようになります。
TestBedの依存性注入設定で、ActivatedRouteを渡してあげています。値としては123を渡しています。

detail.component.spec.ts
import { ActivatedRoute, convertToParamMap } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { DetailComponent } from './detail.component';

describe('DetailComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DetailComponent],
      imports: [RouterTestingModule],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            snapshot: {
              paramMap: convertToParamMap({ id: 123 })
            }
          }
        }
      ]
    });
  }));
});

環境

  • Angular 7.1.0
8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6