2
私は、JasmineとKarmaを使って内部的に別の非同期関数を呼び出すAngularJSサービスで非同期メソッドをテストしようとしています。ユニットテストAngularJS ES6で約束
export default class SearchUserAPI {
constructor(BaseService, $q) {
this.q_ = $q;
this.service_ = BaseService;
}
isActive(email) {
const params = {'email': email};
return this.service_.getUser(params).then(isActive => {
// This part cannot be reached.
console.log('Is Active');
// I need to test the following logic.
return isActive ? true : this.q_.reject(`User ${email} is not active.`);
});
}
}
そして、ここに私のテストはどのように見えるかです::私はチュートリアルの多くに見
import SearchUserApi from './api.service';
let service,
mockedService,
$q;
const email = '[email protected]';
const expectedParams = {email: email};
describe('Search API unit tests', function() {
beforeEach(inject(_$q_ => {
$q = _$q_;
mockedService = {};
service = new SearchUserApi(mockedService, $q);
}));
// This test passes, but it doesn't reach the logging statement in main method.
it('is verifying that Chuck Norris should be active',() => {
// Trying to mock getUser() to return a promise that resolves to true.
mockedService.getUser = jasmine.createSpy('getUser').and.returnValue($q.when(true));
service.isActive(email).then(result => {
// The following should fail, but since this part is called asynchronously and tests end before this expression is called, I never get an error for this.
expect(result).toBe(false);
});
// This test passes, but I'm not too sure how I can verify that isActive(email) returns true for user.
expect(mockedService.getUser).toHaveBeenCalledWith(expectedParams);
});
});
、彼らは$スコープを使用しての話をしてに適用されます。ここ
は私のサービスがどのように見えるかですスコープ変数が変更されているかどうかを確認してください。しかし、私の場合は、$ scope.apply()を使用するためにインスタンス変数(スコープ)を操作していません。
どのように私の非同期呼び出しが終了する前に解決するのを待つためのテストを行うことができますか?
非同期ではありません。 $ q約束は同期的ですが、ダイジェストに依存し、手動でトリガする必要があります。この作業を楽にするためにhttps://github.com/bvaughn/jasmine-promise-matchersをチェックしてください。 – estus