0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Angular】TimeoutErrorが発生する単体テストを作成する。

Posted at

わざとTimeoutErrorを発生させる記事が探しても見当たらなかったため、備忘録として残しておきます。

テスト対象クラス

以下、HelloWorldServiceに対してテストを行います。

hello-world.service.ts
@Injectable({ providedIn: 'root' })
export class HelloWorldService {

  item: string = '';

  constructor(private requestService: RequestService) { }

  public setItemList(): void {
    // getItem() → Observable型のレスポンスDtoが返却されるメソッド
    this.requestService.getItem().pipe(
      map(
        response => {
          this.item = response.item
        }
      ),
      // Timeoutを2秒に設定
      timeout(2000),
      catchError((error) => {
        return throwError(() => error);
      })
    ).subscribe()
  }
}

テストクラス

続いて、テストクラスです。
Mock化したクラスに対して、返却される値(Observable型のレスポンスDto)を指定します。
返却される値に対して、pipe(delay(3000)) を使用します。
上記を行うことで、3秒処理を遅らせることができるため、TimeoutErrorが発生します。

hello-world.service.spec.ts
describe('HelloWorldService', () => {
  let helloWorldService: HelloWorldService;
  let requestService: jasmine.SpyObj<RequestService>;
  let response: Observable<Item>;

  response = of({
    item: 'テスト'
  });

  beforeEach(() => {
    TestBed.configureTestingModule(
      { providers: [HelloWorldService, { provide: RequestService, useValue: jasmine.createSpyObj('RequestService', ['getItem']) }] }
    )

    requestService = TestBed.inject(RequestService) as jasmine.SpyObj<RequestService>;
    // mock化して返却される値をテスト内で指定する。
    // pipe(delay(3000))を付与して、処理を3秒遅らせる。
    requestService.getItem.and.returnValue(<any>response.pipe(delay(3000)));
    helloWorldService = new HelloWorldService(requestService);
  });

  it('テスト', fakeAsync(() => {
      helloWorldService.setItemList();
  }));
});

実行結果

image.png

無事、TimeoutErrorを発生させることができました。
単体テストの参考になれば...

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?