LoginSignup
1
0

More than 3 years have passed since last update.

Jasmine、 PromiseでErrorをThrowするメソッドのテスト

Last updated at Posted at 2020-03-04

Jasmine 3.3

Jasmine 3.3以降だと簡単らしい。まとめると当たり前のメモ、、。
Asyncのメソッドは慣れてないとしんどい。

test.service.ts
export class TestService {
  obj: Something

  async test() {
    await func(); 
    //funcメソットで、下が帰ってくるような場合
    //new Promise((reject) => {reject(new Error('Some Error is occured!')); }
  }
}

Jasmine 3.3 以降だとexpectAsyncにtoBeRejectedWithのMatcherが利用可能なので、それで簡単に補足可能
https://jasmine.github.io/api/3.3/async-matchers.html

test.service.spec.ts
describe('TestService', () => {
let testService: TestService();

  beforeEach(() => {
    testService = new TestService(); //サービスの初期化
  });

  it('test') async () =>{ //とりあえず普通にasync
    await expectAsync(testService.test())
    .toBeRejectedWith(new Error('Some Error is occured!'))
  });
});

ExpectAsyncやtoBeRejectedWithを使わないのであれば、テスト側でcatchすれば良い。

test.service.spec.ts
describe('TestService', () => {
let testService: TestService();

  beforeEach(() => {
    testService = new TestService(); //サービスの初期化
  });

  it('test') () =>{ 
    testService.test().catch((error) => {
      expect('Some Error is occured!').toEqual(error.message);
    })
  });
});

参考

ここもみておくとヨシ!(猫
https://stackoverflow.com/questions/44876306/jasmine-expecting-error-to-be-thrown-in-a-async-function
https://ja.stackoverflow.com/questions/50706/async%E3%81%AE%E4%B8%AD%E3%81%A7%E3%81%A0%E3%81%91-try-catch%E3%81%8Crejected%E3%81%95%E3%82%8C%E3%81%9Fpromise%E3%82%92catch%E3%81%A7%E3%81%8D%E3%82%8B%E7%90%86%E7%94%B1%E3%81%8C%E3%82%8F%E3%81%8B%E3%82%89%E3%81%AA%E3%81%84

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