在Angular 2单元测试中测试Promise <string>值

时间:2016-09-06 07:36:51

标签: angular jasmine angular-promise

Bellow是示例,测试失败-str未定义。         如何从angular2中获得承诺的价值?

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

2 个答案:

答案 0 :(得分:4)

异步执行具有传染性。你不能回去同步执行。

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

我在https://github.com/angular/angular/blob/master/modules/@angular/forms/test/form_array_spec.ts

中查了一下

<强>更新

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

答案 1 :(得分:2)

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);
    }));
});