当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript testing_internal.describe函数代码示例

本文整理汇总了TypeScript中@angular/core/testing/testing_internal.describe函数的典型用法代码示例。如果您正苦于以下问题:TypeScript describe函数的具体用法?TypeScript describe怎么用?TypeScript describe使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了describe函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: describe

  describe('JavaScriptEmitter', () => {
    let emitter: JavaScriptEmitter;
    let someVar: o.ReadVarExpr;

    beforeEach(() => {
      emitter = new JavaScriptEmitter(new SimpleJsImportGenerator());
      someVar = o.variable('someVar');
    });

    function emitStmt(stmt: o.Statement, exportedVars: string[] = null): string {
      if (!exportedVars) {
        exportedVars = [];
      }
      return emitter.emitStatements(someModuleUrl, [stmt], exportedVars);
    }

    it('should declare variables', () => {
      expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt())).toEqual(`var someVar = 1;`);
      expect(emitStmt(someVar.set(o.literal(1)).toDeclStmt(), ['someVar'])).toEqual([
        'var someVar = 1;',
        `Object.defineProperty(exports, 'someVar', { get: function() { return someVar; }});`
      ].join('\n'));
    });

    it('should read and write variables', () => {
      expect(emitStmt(someVar.toStmt())).toEqual(`someVar;`);
      expect(emitStmt(someVar.set(o.literal(1)).toStmt())).toEqual(`someVar = 1;`);
      expect(emitStmt(someVar.set(o.variable('someOtherVar').set(o.literal(1))).toStmt()))
          .toEqual(`someVar = (someOtherVar = 1);`);
    });

    it('should read and write keys', () => {
      expect(emitStmt(o.variable('someMap').key(o.variable('someKey')).toStmt()))
          .toEqual(`someMap[someKey];`);
      expect(emitStmt(o.variable('someMap').key(o.variable('someKey')).set(o.literal(1)).toStmt()))
          .toEqual(`someMap[someKey] = 1;`);
    });

    it('should read and write properties', () => {
      expect(emitStmt(o.variable('someObj').prop('someProp').toStmt()))
          .toEqual(`someObj.someProp;`);
      expect(emitStmt(o.variable('someObj').prop('someProp').set(o.literal(1)).toStmt()))
          .toEqual(`someObj.someProp = 1;`);
    });

    it('should invoke functions and methods and constructors', () => {
      expect(emitStmt(o.variable('someFn').callFn([o.literal(1)]).toStmt())).toEqual('someFn(1);');
      expect(emitStmt(o.variable('someObj').callMethod('someMethod', [o.literal(1)]).toStmt()))
          .toEqual('someObj.someMethod(1);');
      expect(emitStmt(o.variable('SomeClass').instantiate([o.literal(1)]).toStmt()))
          .toEqual('new SomeClass(1);');
    });

    it('should support builtin methods', () => {
      expect(emitStmt(o.variable('arr1')
                          .callMethod(o.BuiltinMethod.ConcatArray, [o.variable('arr2')])
                          .toStmt()))
          .toEqual('arr1.concat(arr2);');

      expect(emitStmt(o.variable('observable')
                          .callMethod(o.BuiltinMethod.SubscribeObservable, [o.variable('listener')])
                          .toStmt()))
          .toEqual('observable.subscribe(listener);');

      expect(
          emitStmt(
              o.variable('fn').callMethod(o.BuiltinMethod.Bind, [o.variable('someObj')]).toStmt()))
          .toEqual('fn.bind(someObj);');
    });

    it('should support literals', () => {
      expect(emitStmt(o.literal(0).toStmt())).toEqual('0;');
      expect(emitStmt(o.literal(true).toStmt())).toEqual('true;');
      expect(emitStmt(o.literal('someStr').toStmt())).toEqual(`'someStr';`);
      expect(emitStmt(o.literalArr([o.literal(1)]).toStmt())).toEqual(`[1];`);
      expect(emitStmt(o.literalMap([['someKey', o.literal(1)]]).toStmt())).toEqual(`{someKey: 1};`);
    });

    it('should support blank literals', () => {
      expect(emitStmt(o.literal(null).toStmt())).toEqual('null;');
      expect(emitStmt(o.literal(undefined).toStmt())).toEqual('undefined;');
    });

    it('should support external identifiers', () => {
      expect(emitStmt(o.importExpr(sameModuleIdentifier).toStmt())).toEqual('someLocalId;');
      expect(emitStmt(o.importExpr(externalModuleIdentifier).toStmt())).toEqual([
        `var import0 = re` +
            `quire('somePackage/someOtherPath');`,
        `import0.someExternalId;`
      ].join('\n'));
    });

    it('should support operators', () => {
      const lhs = o.variable('lhs');
      const rhs = o.variable('rhs');
      expect(emitStmt(o.not(someVar).toStmt())).toEqual('!someVar;');
      expect(
          emitStmt(someVar.conditional(o.variable('trueCase'), o.variable('falseCase')).toStmt()))
          .toEqual('(someVar? trueCase: falseCase);');

//.........这里部分代码省略.........
开发者ID:AlmogShaul,项目名称:angular,代码行数:101,代码来源:js_emitter_spec.ts

示例2: getDOM

  t.describe('HTML sanitizer', () => {
    let originalLog: (msg: any) => any = null;
    let logMsgs: string[];

    t.beforeEach(() => {
      logMsgs = [];
      originalLog = getDOM().log;  // Monkey patch DOM.log.
      getDOM().log = (msg) => logMsgs.push(msg);
    });
    t.afterEach(() => { getDOM().log = originalLog; });

    t.it('serializes nested structures', () => {
      t.expect(sanitizeHtml('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>'))
          .toEqual('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>');
      t.expect(logMsgs).toEqual([]);
    });
    t.it('serializes self closing elements', () => {
      t.expect(sanitizeHtml('<p>Hello <br> World</p>')).toEqual('<p>Hello <br> World</p>');
    });
    t.it('supports namespaced elements', () => {
      t.expect(sanitizeHtml('a<my:hr/><my:div>b</my:div>c')).toEqual('abc');
    });
    t.it('supports namespaced attributes', () => {
      t.expect(sanitizeHtml('<a xlink:href="something">t</a>'))
          .toEqual('<a xlink:href="something">t</a>');
      t.expect(sanitizeHtml('<a xlink:evil="something">t</a>')).toEqual('<a>t</a>');
      t.expect(sanitizeHtml('<a xlink:href="javascript:foo()">t</a>'))
          .toEqual('<a xlink:href="unsafe:javascript:foo()">t</a>');
    });

    t.it('supports sanitizing plain text', () => {
      t.expect(sanitizeHtml('Hello, World')).toEqual('Hello, World');
    });
    t.it('ignores non-element, non-attribute nodes', () => {
      t.expect(sanitizeHtml('<!-- comments? -->no.')).toEqual('no.');
      t.expect(sanitizeHtml('<?pi nodes?>no.')).toEqual('no.');
      t.expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/);
    });
    t.it('escapes entities', () => {
      t.expect(sanitizeHtml('<p>Hello &lt; World</p>')).toEqual('<p>Hello &lt; World</p>');
      t.expect(sanitizeHtml('<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>');
      t.expect(sanitizeHtml('<p alt="% &amp; &quot; !">Hello</p>'))
          .toEqual('<p alt="% &amp; &#34; !">Hello</p>');  // NB: quote encoded as ASCII &#34;.
    });
    t.describe('should strip dangerous elements', () => {
      let dangerousTags = [
        'frameset', 'form', 'param', 'object', 'embed', 'textarea', 'input', 'button', 'option',
        'select', 'script', 'style', 'link', 'base', 'basefont'
      ];

      for (let tag of dangerousTags) {
        t.it(
            `${tag}`, () => { t.expect(sanitizeHtml(`<${tag}>evil!</${tag}>`)).toEqual('evil!'); });
      }
      t.it(`swallows frame entirely`, () => {
        t.expect(sanitizeHtml(`<frame>evil!</frame>`)).not.toContain('<frame>');
      });
    });
    t.describe('should strip dangerous attributes', () => {
      let dangerousAttrs = ['id', 'name', 'style'];

      for (let attr of dangerousAttrs) {
        t.it(`${attr}`, () => {
          t.expect(sanitizeHtml(`<a ${attr}="x">evil!</a>`)).toEqual('<a>evil!</a>');
        });
      }
    });

    if (browserDetection.isWebkit) {
      t.it('should prevent mXSS attacks', function() {
        t.expect(sanitizeHtml('<a href="&#x3000;javascript:alert(1)">CLICKME</a>'))
            .toEqual('<a href="unsafe:javascript:alert(1)">CLICKME</a>');
      });
    }
  });
开发者ID:BharatBhatiya,项目名称:test,代码行数:75,代码来源:html_sanitizer_spec.ts

示例3: main

export function main() {
  /**
   * Tests the PostMessageBus
   */
  describe('MessageBus', () => {
    var bus: MessageBus;

    beforeEach(() => { bus = createConnectedMessageBus(); });

    it('should pass messages in the same channel from sink to source',
       inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
         const CHANNEL = 'CHANNEL 1';
         const MESSAGE = 'Test message';
         bus.initChannel(CHANNEL, false);

         var fromEmitter = bus.from(CHANNEL);
         fromEmitter.subscribe({
           next: (message: any) => {
             expect(message).toEqual(MESSAGE);
             async.done();
           }
         });
         var toEmitter = bus.to(CHANNEL);
         toEmitter.emit(MESSAGE);
       }));

    it('should broadcast', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
         const CHANNEL = 'CHANNEL 1';
         const MESSAGE = 'TESTING';
         const NUM_LISTENERS = 2;
         bus.initChannel(CHANNEL, false);

         var callCount = 0;
         var emitHandler = (message: any) => {
           expect(message).toEqual(MESSAGE);
           callCount++;
           if (callCount == NUM_LISTENERS) {
             async.done();
           }
         };

         for (var i = 0; i < NUM_LISTENERS; i++) {
           var emitter = bus.from(CHANNEL);
           emitter.subscribe({next: emitHandler});
         }

         var toEmitter = bus.to(CHANNEL);
         toEmitter.emit(MESSAGE);
       }));

    it('should keep channels independent',
       inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
         const CHANNEL_ONE = 'CHANNEL 1';
         const CHANNEL_TWO = 'CHANNEL 2';
         const MESSAGE_ONE = 'This is a message on CHANNEL 1';
         const MESSAGE_TWO = 'This is a message on CHANNEL 2';
         var callCount = 0;
         bus.initChannel(CHANNEL_ONE, false);
         bus.initChannel(CHANNEL_TWO, false);

         var firstFromEmitter = bus.from(CHANNEL_ONE);
         firstFromEmitter.subscribe({
           next: (message: any) => {
             expect(message).toEqual(MESSAGE_ONE);
             callCount++;
             if (callCount == 2) {
               async.done();
             }
           }
         });
         var secondFromEmitter = bus.from(CHANNEL_TWO);
         secondFromEmitter.subscribe({
           next: (message: any) => {
             expect(message).toEqual(MESSAGE_TWO);
             callCount++;
             if (callCount == 2) {
               async.done();
             }
           }
         });

         var firstToEmitter = bus.to(CHANNEL_ONE);
         firstToEmitter.emit(MESSAGE_ONE);

         var secondToEmitter = bus.to(CHANNEL_TWO);
         secondToEmitter.emit(MESSAGE_TWO);
       }));
  });

  describe('PostMessageBusSink', () => {
    var bus: MessageBus;
    const CHANNEL = 'Test Channel';

    function setup(runInZone: boolean, zone: NgZone) {
      bus.attachToZone(zone);
      bus.initChannel(CHANNEL, runInZone);
    }

    /**
     * Flushes pending messages and then runs the given function.
//.........这里部分代码省略.........
开发者ID:awerlang,项目名称:angular,代码行数:101,代码来源:message_bus_spec.ts

示例4: describe

  describe('FormArray', () => {
    describe('adding/removing', () => {
      let a: FormArray;
      let c1: FormControl, c2: FormControl, c3: FormControl;

      beforeEach(() => {
        a = new FormArray([]);
        c1 = new FormControl(1);
        c2 = new FormControl(2);
        c3 = new FormControl(3);
      });

      it('should support pushing', () => {
        a.push(c1);
        expect(a.length).toEqual(1);
        expect(a.controls).toEqual([c1]);
      });

      it('should support removing', () => {
        a.push(c1);
        a.push(c2);
        a.push(c3);

        a.removeAt(1);

        expect(a.controls).toEqual([c1, c3]);
      });

      it('should support inserting', () => {
        a.push(c1);
        a.push(c3);

        a.insert(1, c2);

        expect(a.controls).toEqual([c1, c2, c3]);
      });
    });

    describe('value', () => {
      it('should be the reduced value of the child controls', () => {
        const a = new FormArray([new FormControl(1), new FormControl(2)]);
        expect(a.value).toEqual([1, 2]);
      });

      it('should be an empty array when there are no child controls', () => {
        const a = new FormArray([]);
        expect(a.value).toEqual([]);
      });
    });

    describe('setValue', () => {
      let c: FormControl, c2: FormControl, a: FormArray;

      beforeEach(() => {
        c = new FormControl('');
        c2 = new FormControl('');
        a = new FormArray([c, c2]);
      });

      it('should set its own value', () => {
        a.setValue(['one', 'two']);
        expect(a.value).toEqual(['one', 'two']);
      });

      it('should set child values', () => {
        a.setValue(['one', 'two']);
        expect(c.value).toEqual('one');
        expect(c2.value).toEqual('two');
      });

      it('should set values for disabled child controls', () => {
        c2.disable();
        a.setValue(['one', 'two']);
        expect(c2.value).toEqual('two');
        expect(a.value).toEqual(['one']);
        expect(a.getRawValue()).toEqual(['one', 'two']);
      });

      it('should set value for disabled arrays', () => {
        a.disable();
        a.setValue(['one', 'two']);
        expect(c.value).toEqual('one');
        expect(c2.value).toEqual('two');
        expect(a.value).toEqual(['one', 'two']);
      });

      it('should set parent values', () => {
        const form = new FormGroup({'parent': a});
        a.setValue(['one', 'two']);
        expect(form.value).toEqual({'parent': ['one', 'two']});
      });

      it('should not update the parent explicitly specified', () => {
        const form = new FormGroup({'parent': a});
        a.setValue(['one', 'two'], {onlySelf: true});

        expect(form.value).toEqual({parent: ['', '']});
      });

      it('should throw if fields are missing from supplied value (subset)', () => {
//.........这里部分代码省略.........
开发者ID:AlmogShaul,项目名称:angular,代码行数:101,代码来源:form_array_spec.ts

示例5: describe

  describe('PathLocationStrategy', () => {
    var platformLocation, locationStrategy;

    beforeEachProviders(() => [
      PathLocationStrategy,
      {provide: PlatformLocation, useFactory: makeSpyPlatformLocation}
    ]);

    it('should throw without a base element or APP_BASE_HREF', () => {
      platformLocation = new SpyPlatformLocation();
      platformLocation.pathname = '';
      platformLocation.spy('getBaseHrefFromDOM').andReturn(null);

      expect(() => new PathLocationStrategy(platformLocation))
          .toThrowError(
              'No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.');
    });

    describe('without APP_BASE_HREF', () => {
      beforeEach(inject([PlatformLocation, PathLocationStrategy], (pl, ls) => {
        platformLocation = pl;
        locationStrategy = ls;
      }));

      it('should prepend urls with a hash for non-empty URLs', () => {
        expect(locationStrategy.prepareExternalUrl('foo')).toEqual('foo');

        locationStrategy.pushState(null, 'Title', 'foo', '');
        expect(platformLocation.spy('pushState')).toHaveBeenCalledWith(null, 'Title', 'foo');
      });

      it('should prepend urls with a hash for URLs with query params', () => {
        expect(locationStrategy.prepareExternalUrl('foo?bar')).toEqual('foo?bar');

        locationStrategy.pushState(null, 'Title', 'foo', 'bar=baz');
        expect(platformLocation.spy('pushState'))
            .toHaveBeenCalledWith(null, 'Title', 'foo?bar=baz');
      });

      it('should not prepend a hash to external urls for an empty internal URL', () => {
        expect(locationStrategy.prepareExternalUrl('')).toEqual('');

        locationStrategy.pushState(null, 'Title', '', '');
        expect(platformLocation.spy('pushState')).toHaveBeenCalledWith(null, 'Title', '');
      });
    });

    describe('with APP_BASE_HREF with neither leading nor trailing slash', () => {
      beforeEachProviders(() => [{provide: APP_BASE_HREF, useValue: 'app'}]);

      beforeEach(inject([PlatformLocation, PathLocationStrategy], (pl, ls) => {
        platformLocation = pl;
        locationStrategy = ls;
        platformLocation.spy('pushState');
        platformLocation.pathname = '';
      }));

      it('should prepend urls with a hash for non-empty URLs', () => {
        expect(locationStrategy.prepareExternalUrl('foo')).toEqual('app/foo');

        locationStrategy.pushState(null, 'Title', 'foo', '');
        expect(platformLocation.spy('pushState')).toHaveBeenCalledWith(null, 'Title', 'app/foo');
      });

      it('should prepend urls with a hash for URLs with query params', () => {
        expect(locationStrategy.prepareExternalUrl('foo?bar')).toEqual('app/foo?bar');

        locationStrategy.pushState(null, 'Title', 'foo', 'bar=baz');
        expect(platformLocation.spy('pushState'))
            .toHaveBeenCalledWith(null, 'Title', 'app/foo?bar=baz');
      });

      it('should not prepend a hash to external urls for an empty internal URL', () => {
        expect(locationStrategy.prepareExternalUrl('')).toEqual('app');

        locationStrategy.pushState(null, 'Title', '', '');
        expect(platformLocation.spy('pushState')).toHaveBeenCalledWith(null, 'Title', 'app');
      });
    });

    describe('with APP_BASE_HREF with leading slash', () => {
      beforeEachProviders(() => [{provide: APP_BASE_HREF, useValue: '/app'}]);

      beforeEach(inject([PlatformLocation, PathLocationStrategy], (pl, ls) => {
        platformLocation = pl;
        locationStrategy = ls;
        platformLocation.spy('pushState');
        platformLocation.pathname = '';
      }));

      it('should prepend urls with a hash for non-empty URLs', () => {
        expect(locationStrategy.prepareExternalUrl('foo')).toEqual('/app/foo');

        locationStrategy.pushState(null, 'Title', 'foo', '');
        expect(platformLocation.spy('pushState')).toHaveBeenCalledWith(null, 'Title', '/app/foo');
      });

      it('should prepend urls with a hash for URLs with query params', () => {
        expect(locationStrategy.prepareExternalUrl('foo?bar')).toEqual('/app/foo?bar');

//.........这里部分代码省略.........
开发者ID:Coco-wan,项目名称:angular,代码行数:101,代码来源:path_location_strategy_spec.ts

示例6: main

export function main() {
  describe('switch', () => {
    beforeEachProviders(() => [provide(NgLocalization, {useClass: TestLocalizationMap})]);

    it('should display the template according to the exact value',
       inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
         var template = '<div>' +
                        '<ul [ngPlural]="switchValue">' +
                        '<template ngPluralCase="=0"><li>you have no messages.</li></template>' +
                        '<template ngPluralCase="=1"><li>you have one message.</li></template>' +
                        '</ul></div>';

         tcb.overrideTemplate(TestComponent, template)
             .createAsync(TestComponent)
             .then((fixture) => {
               fixture.debugElement.componentInstance.switchValue = 0;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('you have no messages.');

               fixture.debugElement.componentInstance.switchValue = 1;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('you have one message.');

               async.done();
             });
       }));

    it('should display the template according to the category',
       inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
         var template =
             '<div>' +
             '<ul [ngPlural]="switchValue">' +
             '<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
             '<template ngPluralCase="many"><li>you have many messages.</li></template>' +
             '</ul></div>';

         tcb.overrideTemplate(TestComponent, template)
             .createAsync(TestComponent)
             .then((fixture) => {
               fixture.debugElement.componentInstance.switchValue = 2;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('you have a few messages.');

               fixture.debugElement.componentInstance.switchValue = 8;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('you have many messages.');

               async.done();
             });
       }));

    it('should default to other when no matches are found',
       inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
         var template =
             '<div>' +
             '<ul [ngPlural]="switchValue">' +
             '<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
             '<template ngPluralCase="other"><li>default message.</li></template>' +
             '</ul></div>';

         tcb.overrideTemplate(TestComponent, template)
             .createAsync(TestComponent)
             .then((fixture) => {
               fixture.debugElement.componentInstance.switchValue = 100;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('default message.');

               async.done();
             });
       }));

    it('should prioritize value matches over category matches',
       inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async) => {
         var template =
             '<div>' +
             '<ul [ngPlural]="switchValue">' +
             '<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
             '<template ngPluralCase="=2">you have two messages.</template>' +
             '</ul></div>';

         tcb.overrideTemplate(TestComponent, template)
             .createAsync(TestComponent)
             .then((fixture) => {
               fixture.debugElement.componentInstance.switchValue = 2;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('you have two messages.');

               fixture.debugElement.componentInstance.switchValue = 3;
               fixture.detectChanges();
               expect(fixture.debugElement.nativeElement).toHaveText('you have a few messages.');

               async.done();
             });
       }));
  });
}
开发者ID:0xJoKe,项目名称:angular,代码行数:96,代码来源:ng_plural_spec.ts

示例7: describe

  describe('Testability', () => {
    let testability: Testability;
    let execute: any;
    let execute2: any;
    let ngZone: MockNgZone;

    beforeEach(() => {
      ngZone = new MockNgZone();
      testability = new Testability(ngZone);
      execute = new SpyObject().spy('execute');
      execute2 = new SpyObject().spy('execute');
    });

    describe('Pending count logic', () => {
      it('should start with a pending count of 0',
         () => { expect(testability.getPendingRequestCount()).toEqual(0); });

      it('should fire whenstable callbacks if pending count is 0',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           testability.whenStable(execute);
           microTask(() => {
             expect(execute).toHaveBeenCalled();
             async.done();
           });
         }));

      it('should not fire whenstable callbacks synchronously if pending count is 0', () => {
        testability.whenStable(execute);
        expect(execute).not.toHaveBeenCalled();
      });

      it('should not call whenstable callbacks when there are pending counts',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           testability.increasePendingRequestCount();
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).not.toHaveBeenCalled();
               async.done();
             });
           });
         }));

      it('should fire whenstable callbacks when pending drops to 0',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).toHaveBeenCalled();
               async.done();
             });
           });
         }));

      it('should not fire whenstable callbacks synchronously when pending drops to 0', () => {
        testability.increasePendingRequestCount();
        testability.whenStable(execute);
        testability.decreasePendingRequestCount();

        expect(execute).not.toHaveBeenCalled();
      });

      it('should fire whenstable callbacks with didWork if pending count is 0',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           testability.whenStable(execute);
           microTask(() => {
             expect(execute).toHaveBeenCalledWith(false);
             async.done();
           });
         }));

      it('should fire whenstable callbacks with didWork when pending drops to 0',
         inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).toHaveBeenCalledWith(true);
               testability.whenStable(execute2);

               microTask(() => {
                 expect(execute2).toHaveBeenCalledWith(false);
                 async.done();
               });
             });
           });
         }));
//.........这里部分代码省略.........
开发者ID:AlmogShaul,项目名称:angular,代码行数:101,代码来源:testability_spec.ts

示例8: describe

  describe('fake async', () => {
    it('should run synchronous code', () => {
      var ran = false;
      fakeAsync(() => { ran = true; })();

      expect(ran).toEqual(true);
    });

    it('should pass arguments to the wrapped function', () => {
      fakeAsync((foo: any /** TODO #9100 */, bar: any /** TODO #9100 */) => {
        expect(foo).toEqual('foo');
        expect(bar).toEqual('bar');
      })('foo', 'bar');
    });

    it('should work with inject()', fakeAsync(inject([Parser], (parser: any /** TODO #9100 */) => {
         expect(parser).toBeAnInstanceOf(Parser);
       })));

    it('should throw on nested calls', () => {
      expect(() => {
        fakeAsync(() => { fakeAsync((): any /** TODO #9100 */ => null)(); })();
      }).toThrowError('fakeAsync() calls can not be nested');
    });

    it('should flush microtasks before returning', () => {
      var thenRan = false;

      fakeAsync(() => { resolvedPromise.then(_ => { thenRan = true; }); })();

      expect(thenRan).toEqual(true);
    });


    it('should propagate the return value',
       () => { expect(fakeAsync(() => 'foo')()).toEqual('foo'); });

    describe('Promise', () => {
      it('should run asynchronous code', fakeAsync(() => {
           var thenRan = false;
           resolvedPromise.then((_) => { thenRan = true; });

           expect(thenRan).toEqual(false);

           flushMicrotasks();
           expect(thenRan).toEqual(true);
         }));

      it('should run chained thens', fakeAsync(() => {
           var log = new Log();

           resolvedPromise.then((_) => log.add(1)).then((_) => log.add(2));

           expect(log.result()).toEqual('');

           flushMicrotasks();
           expect(log.result()).toEqual('1; 2');
         }));

      it('should run Promise created in Promise', fakeAsync(() => {
           var log = new Log();

           resolvedPromise.then((_) => {
             log.add(1);
             resolvedPromise.then((_) => log.add(2));
           });

           expect(log.result()).toEqual('');

           flushMicrotasks();
           expect(log.result()).toEqual('1; 2');
         }));

      it('should complain if the test throws an exception during async calls', () => {
        expect(() => {
          fakeAsync(() => {
            resolvedPromise.then((_) => { throw new BaseException('async'); });
            flushMicrotasks();
          })();
        }).toThrowError('Uncaught (in promise): async');
      });

      it('should complain if a test throws an exception', () => {
        expect(() => {
          fakeAsync(() => { throw new BaseException('sync'); })();
        }).toThrowError('sync');
      });

    });

    describe('timers', () => {
      it('should run queued zero duration timer on zero tick', fakeAsync(() => {
           var ran = false;
           setTimeout(() => { ran = true; }, 0);

           expect(ran).toEqual(false);

           tick();
           expect(ran).toEqual(true);
         }));
//.........这里部分代码省略.........
开发者ID:JamieMoon,项目名称:angular,代码行数:101,代码来源:fake_async_spec.ts


注:本文中的@angular/core/testing/testing_internal.describe函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。