2

Bellow is example,and test failed- str is undefined. How get value from promise in angular2 ?

 describe('Test', () => {
        it('case of string', () => {
            let t: Promise<string> = deserializeSimpleField(...);
            let str:string;
            t.then(value=>str = value);
            expect(str).toEqual('name');
        });});
emanuel07
  • 738
  • 12
  • 27

2 Answers2

4

Async execution is contagious. You can't go back to sync execution.

describe('Test', () => {
    it('case of string', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
        deserializeSimpleField(...)
        .then(value => {
          expect(value).toEqual('name');
          async.done();
        });
    });
});

I looked it up in https://github.com/angular/angular/blob/master/modules/@angular/forms/test/form_array_spec.ts

update

describe('Test', () => {
    it('case of string', async(() => {
        return deserializeSimpleField(...)
        .then(value => {
          expect(value).toEqual('name');
          async.done();
        });
    }));
});
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Dear @Gunter I use @angular/testing ,and there AsyncTestCompleter is missing?. Is exists way do it by @angular/testing? – emanuel07 Sep 06 '16 at 10:14
  • actually I don't know what the correct and current way is to do async testing. I wasn't able to find anything in the changelog neither. I just looked up a test in the github repo that was recently updated. Can you please try my updated answer? (not sure if the added `return` is required). – Günter Zöchbauer Sep 06 '16 at 10:21
  • updated version brings : TypeError: AsyncTestZoneSpec is not a constructor at runInAsyncTestZone – emanuel07 Sep 06 '16 at 10:54
  • Sorry, out of ideas. – Günter Zöchbauer Sep 06 '16 at 11:13
  • 1
    Thank you very match,for ideas dear @Gunter – emanuel07 Sep 06 '16 at 11:27
  • The updated approach is also used in https://github.com/angular/angular.io/pull/2198/files Perhaps these docs can help you to figure out how to fix your issue. – Günter Zöchbauer Sep 06 '16 at 13:36
  • You don't need the done() method as this is run in a zone in Angular 2 - see https://stackoverflow.com/questions/40126729/angular-2-testing-async-function-call-when-to-use#40127164 – Ben Taliadoros Aug 24 '17 at 12:17
3
I resolve question following way,(using  fakeAsync,tick..)

require('zone.js/dist/fake-async-test');
import {describe, it, expect, fakeAsync, tick} from '@angular/testing'
describe('my first test', () => {
    it('Promises fulfilled by tick',fakeAsync((): void => {
        let promise:Promise<number> =Promise.resolve(11);
        let x:number;
        promise.then( v => {
            x = v;
        });
        tick();
        expect(x).toBe(11);
    }));
});
emanuel07
  • 738
  • 12
  • 27