本文整理汇总了TypeScript中@angular/core/testing.fakeAsync函数的典型用法代码示例。如果您正苦于以下问题:TypeScript fakeAsync函数的具体用法?TypeScript fakeAsync怎么用?TypeScript fakeAsync使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fakeAsync函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: describe
//.........这里部分代码省略.........
title: undefined,
settings: { name: 'mariko', description: undefined },
images: []
};
component.ngOnChanges();
expect(component.block.hide).toBeFalsy();
});
it("should show if there is a descriton", () => {
component.block = {
id: 1,
title: undefined,
settings: { name: undefined, description: 'nice manga' },
images: []
};
component.ngOnChanges();
expect(component.block.hide).toBeFalsy();
});
it("should show if there is an image", () => {
component.block = {
id: 1,
title: undefined,
settings: { name: undefined, description: undefined },
images: [{
id: 1, filename: "file1.png",
url: "/image_uploads/0000/0005/file1.png"
}]
};
component.ngOnChanges();
expect(component.block.hide).toBeFalsy();
});
it("initialize modifiedLink link", fakeAsync(() => {
component.ngOnInit();
tick();
expect(component.modifiedLink).toEqual(block.settings);
}));
it("should display section name", () => {
expect(fixture.debugElement.nativeElement.querySelector(".section-block .name").innerHTML).toContain(block.settings.name);
});
it("should display section description", () => {
expect(fixture.debugElement.nativeElement.querySelector(".section-block .description").innerHTML).toContain(block.settings.description);
});
it("should return the last image of component images list", () => {
expect(component.getSectionImage()).toEqual(block.images[1]);
});
it("should return null if there is an empty array in component images list", () => {
component.block.images = [];
expect(component.getSectionImage()).toBeNull();
});
it("should return null if images block attribute is null", () => {
component.block.images = null;
expect(component.getSectionImage()).toBeNull();
});
it("should show the last image from block images", () => {
expect(fixture.debugElement.nativeElement.querySelector(".section-image").src).toContain('/image_uploads/0000/0005/file2.png');
});
it("not show image if there is no image", () => {
示例2: describe
describe('template-driven forms integration tests', () => {
beforeEach(() => { TestBed.configureTestingModule({imports: [FormsModule]}); });
it('should support ngModel for single fields',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
const t = `<div><input type="text" [(ngModel)]="name"></div>`;
let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8);
tick();
fixture.debugElement.componentInstance.name = 'oldValue';
fixture.detectChanges();
var input = fixture.debugElement.query(By.css('input')).nativeElement;
tick();
expect(input.value).toEqual('oldValue');
input.value = 'updatedValue';
dispatchEvent(input, 'input');
tick();
expect(fixture.debugElement.componentInstance.name).toEqual('updatedValue');
})));
it('should support ngModel registration with a parent form',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
const t = `
<form>
<input name="first" [(ngModel)]="name" maxlength="4">
</form>
`;
let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8);
tick();
fixture.debugElement.componentInstance.name = 'Nancy';
fixture.detectChanges();
var form = fixture.debugElement.children[0].injector.get(NgForm);
tick();
expect(form.value).toEqual({first: 'Nancy'});
expect(form.valid).toBe(false);
})));
it('should add new controls and control groups',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
const t = `<form>
<div ngModelGroup="user">
<input type="text" name="login" ngModel>
</div>
</form>`;
let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8);
tick();
fixture.debugElement.componentInstance.name = null;
fixture.detectChanges();
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['user']).not.toBeDefined();
tick();
expect(form.controls['user']).toBeDefined();
expect(form.controls['user'].controls['login']).toBeDefined();
})));
it('should emit ngSubmit event on submit',
fakeAsync(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
const t = `<div><form (ngSubmit)="name='updated'"></form></div>`;
let fixture = tcb.overrideTemplate(MyComp8, t).createFakeAsync(MyComp8);
tick();
fixture.debugElement.componentInstance.name = 'old';
var form = fixture.debugElement.query(By.css('form'));
dispatchEvent(form.nativeElement, 'submit');
tick();
expect(fixture.debugElement.componentInstance.name).toEqual('updated');
})));
it('should mark NgForm as submitted on submit event',
inject([TestComponentBuilder], fakeAsync((tcb: TestComponentBuilder) => {
const t = `<div>
<form #f="ngForm" (ngSubmit)="data=f.submitted"></form>
<span>{{data}}</span>
</div>`;
var fixture: ComponentFixture<MyComp8>;
tcb.overrideTemplate(MyComp8, t).createAsync(MyComp8).then((root) => {
fixture = root;
});
tick();
fixture.debugElement.componentInstance.data = false;
//.........这里部分代码省略.........
示例3: describe
describe('getReadme', () => {
it('should not get the readme if not connected to github', fakeAsync(inject([SampleBusinessNetworkService], (service: SampleBusinessNetworkService) => {
service['octo'] = null;
service.getReadme('myOwner', 'myRepository', 'packages/')
.then(() => {
throw('Should not get here');
})
.catch((error) => {
error.should.equal('no connection to GitHub');
});
tick();
})));
it('should get the readme', fakeAsync(inject([SampleBusinessNetworkService], (service: SampleBusinessNetworkService) => {
let octoReadmeFileMock = {
name: 'README.md',
content: 'YSByZWFkbWUgZmlsZQ=='
};
let repoMock = {
contents: sinon.stub()
};
repoMock.contents.returns({
fetch: sinon.stub().returns(Promise.resolve(octoReadmeFileMock))
});
let octoMock = {
repos: sinon.stub().returns(repoMock)
};
service['octo'] = octoMock;
service.getReadme('myOwner', 'myRepository', 'packages/')
.then((result) => {
result.should.deep.equal({name: 'README.md', data: 'a readme file'});
});
tick();
})));
it('should handle having no readme', fakeAsync(inject([SampleBusinessNetworkService], (service: SampleBusinessNetworkService) => {
let repoMock = {
contents: sinon.stub()
};
repoMock.contents.returns({
fetch: sinon.stub().returns(Promise.reject({status: 404}))
});
let octoMock = {
repos: sinon.stub().returns(repoMock)
};
service['octo'] = octoMock;
service.getReadme('myOwner', 'myRepository', 'packages/')
.then((result) => {
should.not.exist(result);
});
tick();
})));
it('should handle error', fakeAsync(inject([SampleBusinessNetworkService], (service: SampleBusinessNetworkService) => {
let repoMock = {
contents: sinon.stub()
};
repoMock.contents.returns({
fetch: sinon.stub().returns(Promise.reject('some error'))
});
let octoMock = {
repos: sinon.stub().returns(repoMock)
};
service['octo'] = octoMock;
service.getReadme('myOwner', 'myRepository', 'packages/')
.then(() => {
throw('should not get here');
})
.catch((error) => {
error.should.equal('some error');
});
tick();
})));
});
示例4: describe
describe('Angulartics2GoogleGlobalSiteTag', () => {
let gtag: any;
let ga: any;
let fixture: ComponentFixture<any>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TestModule],
providers: [Angulartics2GoogleGlobalSiteTag],
});
window.gtag = gtag = jasmine.createSpy('gtag');
window.ga = ga = {
getAll: function() {
return {
forEach: function(callback) {
const tracker = {
get: function(value) {
return 'UA-111111111-1';
},
};
callback(tracker);
},
};
},
};
});
it('should track pages',
fakeAsync(inject([Angulartics2, Angulartics2GoogleGlobalSiteTag],
(angulartics2: Angulartics2, angulartics2GoogleGlobalSiteTag: Angulartics2GoogleGlobalSiteTag) => {
fixture = createRoot(RootCmp);
angulartics2.pageTrack.next({ path: '/abc' });
advance(fixture);
expect(gtag.calls.count()).toEqual(1);
expect(gtag).toHaveBeenCalledWith('config', 'UA-111111111-1', {'page_path': '/abc'});
},
)),
);
it('should track events',
fakeAsync(inject([Angulartics2, Angulartics2GoogleGlobalSiteTag],
(angulartics2: Angulartics2, angulartics2GoogleGlobalSiteTag: Angulartics2GoogleGlobalSiteTag) => {
fixture = createRoot(RootCmp);
angulartics2.eventTrack.next({
action: 'do',
properties: {
value: 1,
label: 'abc',
gstCustom: {
customKey: 'customValue',
},
}
});
advance(fixture);
expect(gtag).toHaveBeenCalledWith('event', 'do', {
event_category: 'interaction',
event_label: 'abc',
value: 1,
non_interaction: undefined,
customKey: 'customValue',
});
}
)),
);
it('should track exceptions',
fakeAsync(inject([Angulartics2, Angulartics2GoogleGlobalSiteTag],
(angulartics2: Angulartics2, angulartics2GoogleGlobalSiteTag: Angulartics2GoogleGlobalSiteTag) => {
fixture = createRoot(RootCmp);
angulartics2.exceptionTrack.next({ description: 'bugger', gstCustom: { appId: 'app', appName: 'Test App', appVersion: '0.1' } });
advance(fixture);
expect(gtag).toHaveBeenCalledWith('event', 'exception', {
event_category: 'interaction',
event_label: undefined,
value: undefined,
non_interaction: undefined,
description: 'bugger',
fatal: true,
appId: 'app',
appName: 'Test App',
appVersion: '0.1',
});
}
)),
);
});
示例5: describe
describe('ngOninit', () => {
it('should initialise the footer', fakeAsync(inject([XHRBackend, ConfigService], (mockBackend, configService: ConfigService) => {
let myConfig = new Config();
myConfig.webonly = true;
myConfig.title = 'My Title';
myConfig.banner = ['My', 'Banner'];
myConfig.docURL = 'https://doc_url';
myConfig.links = {
docs: 'My Docs',
tutorial: 'My Tutorial',
community: 'My Community',
github: 'My Github',
install: 'My Install',
legal: 'My License'
};
configService['configLoaded'] = true;
configService['config'] = myConfig;
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponseAboutService)
})));
});
fixture.detectChanges();
tick();
fixture.detectChanges();
component['playgroundVersion'].should.match(/[0-9]+.[0-9]+.[0-9]+/);
component['config'].should.deep.equal(myConfig);
fixture.detectChanges();
tick();
links = fixture.debugElement.queryAll(By.css('a'));
links.length.should.equal(5);
links[0].nativeElement.textContent.should.equal('Legal');
links[1].nativeElement.textContent.should.equal('GitHub');
links[2].nativeElement.textContent.should.equal('Tutorial');
links[3].nativeElement.textContent.should.equal('Docs');
links[4].nativeElement.textContent.should.equal('Community');
})));
it('should load config if not already loaded', fakeAsync(inject([XHRBackend, ConfigService], (mockBackend, configService: ConfigService) => {
let myConfig = new Config();
myConfig.webonly = true;
myConfig.title = 'My Title';
myConfig.banner = ['My', 'Banner'];
myConfig.docURL = 'https://doc_url';
myConfig.links = {
docs: 'My Docs',
tutorial: 'My Tutorial',
community: 'My Community',
github: 'My Github',
install: 'My Install',
legal: 'My License'
};
mockBackend.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body: JSON.stringify(mockResponseConfigService)
})));
});
fixture.detectChanges();
tick();
fixture.detectChanges();
component['config'].should.deep.equal(myConfig);
})));
it('should handle error from about service', fakeAsync(inject([ConfigService, XHRBackend], (configService, mockBackend) => {
let myConfig = new Config();
myConfig.webonly = true;
myConfig.title = 'My Title';
myConfig.banner = ['My', 'Banner'];
myConfig.docURL = 'https://doc_url';
myConfig.links = {
docs: 'My Docs',
tutorial: 'My Tutorial',
community: 'My Community',
github: 'My Github',
install: 'My Install',
legal: 'My License'
};
configService['configLoaded'] = true;
configService['config'] = myConfig;
component['alertService'].errorStatus$.subscribe(
(message) => {
if (message !== null) {
message.should.equal('error');
}
});
mockBackend.connections.subscribe(
//.........这里部分代码省略.........
示例6: describe
describe('asyncValidator', () => {
it('should run validator with the initial value', fakeAsync(() => {
const c = new FormControl('value', null, asyncValidator('expected'));
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true});
}));
it('should support validators returning observables', fakeAsync(() => {
const c = new FormControl('value', null, asyncValidatorReturningObservable);
tick();
expect(c.valid).toEqual(false);
expect(c.errors).toEqual({'async': true});
}));
it('should rerun the validator when the value changes', fakeAsync(() => {
const c = new FormControl('value', null, asyncValidator('expected'));
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should run the async validator only when the sync validator passes', fakeAsync(() => {
const c = new FormControl('', Validators.required, asyncValidator('expected'));
tick();
expect(c.errors).toEqual({'required': true});
c.setValue('some value');
tick();
expect(c.errors).toEqual({'async': true});
}));
it('should mark the control as pending while running the async validation', fakeAsync(() => {
const c = new FormControl('', null, asyncValidator('expected'));
expect(c.pending).toEqual(true);
tick();
expect(c.pending).toEqual(false);
}));
it('should only use the latest async validation run', fakeAsync(() => {
const c = new FormControl(
'', null, asyncValidator('expected', {'long': 200, 'expected': 100}));
c.setValue('long');
c.setValue('expected');
tick(300);
expect(c.valid).toEqual(true);
}));
it('should support arrays of async validator functions if passed', fakeAsync(() => {
const c =
new FormControl('value', null, [asyncValidator('expected'), otherAsyncValidator]);
tick();
expect(c.errors).toEqual({'async': true, 'other': true});
}));
it('should add single async validator', fakeAsync(() => {
const c = new FormControl('value', null);
c.setAsyncValidators(asyncValidator('expected'));
expect(c.asyncValidator).not.toEqual(null);
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should add async validator from array', fakeAsync(() => {
const c = new FormControl('value', null);
c.setAsyncValidators([asyncValidator('expected')]);
expect(c.asyncValidator).not.toEqual(null);
c.setValue('expected');
tick();
expect(c.valid).toEqual(true);
}));
it('should clear async validators', fakeAsync(() => {
const c = new FormControl('value', [asyncValidator('expected'), otherAsyncValidator]);
c.clearValidators();
expect(c.asyncValidator).toEqual(null);
}));
//.........这里部分代码省略.........
示例7: describe
describe('RuntimeCompiler', () => {
let compiler: Compiler;
let resourceLoader: SpyResourceLoader;
let dirResolver: MockDirectiveResolver;
let injector: Injector;
beforeEach(() => { TestBed.configureCompiler({providers: [SpyResourceLoader.PROVIDE]}); });
beforeEach(fakeAsync(inject(
[Compiler, ResourceLoader, DirectiveResolver, Injector],
(_compiler: Compiler, _resourceLoader: SpyResourceLoader,
_dirResolver: MockDirectiveResolver, _injector: Injector) => {
compiler = _compiler;
resourceLoader = _resourceLoader;
dirResolver = _dirResolver;
injector = _injector;
})));
describe('compileModuleAsync', () => {
it('should allow to use templateUrl components', fakeAsync(() => {
@NgModule({
declarations: [SomeCompWithUrlTemplate],
entryComponents: [SomeCompWithUrlTemplate]
})
class SomeModule {
}
resourceLoader.spy('get').and.callFake(() => Promise.resolve('hello'));
let ngModuleFactory: NgModuleFactory<any> = undefined !;
compiler.compileModuleAsync(SomeModule).then((f) => ngModuleFactory = f);
tick();
expect(ngModuleFactory.moduleType).toBe(SomeModule);
}));
});
describe('compileModuleSync', () => {
it('should throw when using a templateUrl that has not been compiled before', () => {
@NgModule(
{declarations: [SomeCompWithUrlTemplate], entryComponents: [SomeCompWithUrlTemplate]})
class SomeModule {
}
resourceLoader.spy('get').and.callFake(() => Promise.resolve(''));
expect(() => compiler.compileModuleSync(SomeModule))
.toThrowError(
`Can't compile synchronously as ${stringify(SomeCompWithUrlTemplate)} is still being loaded!`);
});
it('should throw when using a templateUrl in a nested component that has not been compiled before',
() => {
@NgModule({declarations: [SomeComp, ChildComp], entryComponents: [SomeComp]})
class SomeModule {
}
resourceLoader.spy('get').and.callFake(() => Promise.resolve(''));
dirResolver.setView(SomeComp, new ViewMetadata({template: ''}));
dirResolver.setView(ChildComp, new ViewMetadata({templateUrl: '/someTpl.html'}));
expect(() => compiler.compileModuleSync(SomeModule))
.toThrowError(
`Can't compile synchronously as ${stringify(ChildComp)} is still being loaded!`);
});
it('should allow to use templateUrl components that have been loaded before',
fakeAsync(() => {
@NgModule({
declarations: [SomeCompWithUrlTemplate],
entryComponents: [SomeCompWithUrlTemplate]
})
class SomeModule {
}
resourceLoader.spy('get').and.callFake(() => Promise.resolve('hello'));
compiler.compileModuleAsync(SomeModule);
tick();
const ngModuleFactory = compiler.compileModuleSync(SomeModule);
expect(ngModuleFactory).toBeTruthy();
}));
});
});
示例8: describe
describe('with a custom loader', () => {
// Use a fake custom loader for tests, with helper functions to resolve or reject.
let loader: () => Promise<void>;
let resolveLoader: () => void;
let failLoader: () => void;
// Arbitrary element and listener for testing.
let someElement: HTMLDivElement;
let someListener: () => void;
// Keep track of whatever value is in `window.Hammer` before the test so it can be
// restored afterwards so that this test doesn't care whether Hammer is actually loaded.
let originalHammerGlobal: any;
// Fake Hammer instance ("mc") used to test the underlying event registration.
let fakeHammerInstance: {on: () => void, off: () => void};
// Inject the NgZone so that we can make it available to the plugin through a fake
// EventManager.
let ngZone: NgZone;
beforeEach(inject([NgZone], (z: NgZone) => { ngZone = z; }));
beforeEach(() => {
originalHammerGlobal = (window as any).Hammer;
(window as any).Hammer = undefined;
fakeHammerInstance = {
on: jasmine.createSpy('mc.on'),
off: jasmine.createSpy('mc.off'),
};
loader = () => new Promise((resolve, reject) => {
resolveLoader = resolve;
failLoader = reject;
});
// Make the hammer config return a fake hammer instance
const hammerConfig = new HammerGestureConfig();
spyOn(hammerConfig, 'buildHammer').and.returnValue(fakeHammerInstance);
plugin = new HammerGesturesPlugin(document, hammerConfig, fakeConsole, loader);
// Use a fake EventManager that has access to the NgZone.
plugin.manager = { getZone: () => ngZone } as EventManager;
someElement = document.createElement('div');
someListener = () => {};
});
afterEach(() => { (window as any).Hammer = originalHammerGlobal; });
it('should not log a warning when HammerJS is not loaded', () => {
plugin.addEventListener(someElement, 'swipe', () => {});
expect(fakeConsole.warn).not.toHaveBeenCalled();
});
it('should defer registering an event until Hammer is loaded', fakeAsync(() => {
plugin.addEventListener(someElement, 'swipe', someListener);
expect(fakeHammerInstance.on).not.toHaveBeenCalled();
(window as any).Hammer = {};
resolveLoader();
tick();
expect(fakeHammerInstance.on).toHaveBeenCalledWith('swipe', jasmine.any(Function));
}));
it('should cancel registration if an event is removed before being added', fakeAsync(() => {
const deregister = plugin.addEventListener(someElement, 'swipe', someListener);
deregister();
(window as any).Hammer = {};
resolveLoader();
tick();
expect(fakeHammerInstance.on).not.toHaveBeenCalled();
}));
it('should remove a listener after Hammer is loaded', fakeAsync(() => {
const removeListener = plugin.addEventListener(someElement, 'swipe', someListener);
(window as any).Hammer = {};
resolveLoader();
tick();
removeListener();
expect(fakeHammerInstance.off).toHaveBeenCalledWith('swipe', jasmine.any(Function));
}));
it('should log a warning when the loader fails', fakeAsync(() => {
plugin.addEventListener(someElement, 'swipe', () => {});
failLoader();
tick();
expect(fakeConsole.warn)
.toHaveBeenCalledWith(
`The "swipe" event cannot be bound because the custom Hammer.JS loader failed.`);
}));
it('should load a warning if the loader resolves and Hammer is not present', fakeAsync(() => {
//.........这里部分代码省略.........
示例9: describe
describe('window scroll events', () => {
const SCROLL_EVENT_DELAY = 10;
let onScrollSpy: jasmine.Spy;
beforeEach(() => {
onScrollSpy = spyOn(ScrollSpyService.prototype as any, 'onScroll');
});
it('should be subscribed to when the first group of elements is spied on', fakeAsync(() => {
window.dispatchEvent(new Event('scroll'));
expect(onScrollSpy).not.toHaveBeenCalled();
scrollSpyService.spyOn([]);
window.dispatchEvent(new Event('scroll'));
expect(onScrollSpy).not.toHaveBeenCalled();
tick(SCROLL_EVENT_DELAY);
expect(onScrollSpy).toHaveBeenCalled();
}));
it('should be unsubscribed from when the last group of elements is removed', fakeAsync(() => {
const info1 = scrollSpyService.spyOn([]);
const info2 = scrollSpyService.spyOn([]);
window.dispatchEvent(new Event('scroll'));
tick(SCROLL_EVENT_DELAY);
expect(onScrollSpy).toHaveBeenCalled();
info1.unspy();
onScrollSpy.calls.reset();
window.dispatchEvent(new Event('scroll'));
tick(SCROLL_EVENT_DELAY);
expect(onScrollSpy).toHaveBeenCalled();
info2.unspy();
onScrollSpy.calls.reset();
window.dispatchEvent(new Event('scroll'));
tick(SCROLL_EVENT_DELAY);
expect(onScrollSpy).not.toHaveBeenCalled();
}));
it(`should only fire every ${SCROLL_EVENT_DELAY}ms`, fakeAsync(() => {
scrollSpyService.spyOn([]);
window.dispatchEvent(new Event('scroll'));
tick(SCROLL_EVENT_DELAY - 2);
expect(onScrollSpy).not.toHaveBeenCalled();
window.dispatchEvent(new Event('scroll'));
tick(1);
expect(onScrollSpy).not.toHaveBeenCalled();
window.dispatchEvent(new Event('scroll'));
tick(1);
expect(onScrollSpy).toHaveBeenCalledTimes(1);
onScrollSpy.calls.reset();
tick(SCROLL_EVENT_DELAY / 2);
window.dispatchEvent(new Event('scroll'));
tick(SCROLL_EVENT_DELAY - 2);
expect(onScrollSpy).not.toHaveBeenCalled();
window.dispatchEvent(new Event('scroll'));
tick(1);
expect(onScrollSpy).not.toHaveBeenCalled();
window.dispatchEvent(new Event('scroll'));
tick(1);
expect(onScrollSpy).toHaveBeenCalledTimes(1);
}));
});
示例10: describe
describe('Overlay', () => {
let builder: TestComponentBuilder;
let overlay: Overlay;
let componentPortal: ComponentPortal<PizzaMsg>;
let templatePortal: TemplatePortal;
let overlayContainerElement: HTMLElement;
beforeEach(() => {
addProviders([
Overlay,
OverlayPositionBuilder,
ViewportRuler,
{provide: OverlayContainer, useFactory: () => {
return {
getContainerElement: () => {
if (overlayContainerElement) { return overlayContainerElement; }
overlayContainerElement = document.createElement('div');
return overlayContainerElement;
}
};
}}
]);
});
let deps = [TestComponentBuilder, Overlay];
beforeEach(inject(deps, fakeAsync((tcb: TestComponentBuilder, o: Overlay) => {
builder = tcb;
overlay = o;
builder.createAsync(TestComponentWithTemplatePortals).then(fixture => {
fixture.detectChanges();
templatePortal = fixture.componentInstance.templatePortal;
componentPortal = new ComponentPortal(PizzaMsg, fixture.componentInstance.viewContainerRef);
});
flushMicrotasks();
})));
it('should load a component into an overlay', fakeAsyncTest(() => {
let overlayRef: OverlayRef;
overlay.create().then(ref => {
overlayRef = ref;
overlayRef.attach(componentPortal);
});
flushMicrotasks();
expect(overlayContainerElement.textContent).toContain('Pizza');
overlayRef.dispose();
expect(overlayContainerElement.childNodes.length).toBe(0);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should load a template portal into an overlay', fakeAsyncTest(() => {
let overlayRef: OverlayRef;
overlay.create().then(ref => {
overlayRef = ref;
overlayRef.attach(templatePortal);
});
flushMicrotasks();
expect(overlayContainerElement.textContent).toContain('Cake');
overlayRef.dispose();
expect(overlayContainerElement.childNodes.length).toBe(0);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should open multiple overlays', fakeAsyncTest(() => {
let pizzaOverlayRef: OverlayRef;
let cakeOverlayRef: OverlayRef;
overlay.create().then(ref => {
pizzaOverlayRef = ref;
pizzaOverlayRef.attach(componentPortal);
});
flushMicrotasks();
overlay.create().then(ref => {
cakeOverlayRef = ref;
cakeOverlayRef.attach(templatePortal);
});
flushMicrotasks();
expect(overlayContainerElement.childNodes.length).toBe(2);
expect(overlayContainerElement.textContent).toContain('Pizza');
expect(overlayContainerElement.textContent).toContain('Cake');
pizzaOverlayRef.dispose();
expect(overlayContainerElement.childNodes.length).toBe(1);
expect(overlayContainerElement.textContent).toContain('Cake');
cakeOverlayRef.dispose();
expect(overlayContainerElement.childNodes.length).toBe(0);
//.........这里部分代码省略.........
示例11: fakeAsyncTest
function fakeAsyncTest(fn: () => void) {
return inject([], fakeAsync(fn));
}
示例12: describe
describe('ActivateComponent', () => {
let comp: ActivateComponent;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HipsterBlogTestModule],
declarations: [ActivateComponent],
providers: [
ActivateService,
{
provide: ActivatedRoute,
useValue: new MockActivatedRoute({'key': 'ABC123'})
},
{
provide: LoginModalService,
useValue: null
}
]
}).overrideTemplate(ActivateComponent, '')
.compileComponents();
}));
beforeEach(() => {
const fixture = TestBed.createComponent(ActivateComponent);
comp = fixture.componentInstance;
});
it('calls activate.get with the key from params',
inject([ActivateService],
fakeAsync((service: ActivateService) => {
spyOn(service, 'get').and.returnValue(Observable.of());
comp.ngOnInit();
tick();
expect(service.get).toHaveBeenCalledWith('ABC123');
})
)
);
it('should set set success to OK upon successful activation',
inject([ActivateService],
fakeAsync((service: ActivateService) => {
spyOn(service, 'get').and.returnValue(Observable.of({}));
comp.ngOnInit();
tick();
expect(comp.error).toBe(null);
expect(comp.success).toEqual('OK');
})
)
);
it('should set set error to ERROR upon activation failure',
inject([ActivateService],
fakeAsync((service: ActivateService) => {
spyOn(service, 'get').and.returnValue(Observable.throw('ERROR'));
comp.ngOnInit();
tick();
expect(comp.error).toBe('ERROR');
expect(comp.success).toEqual(null);
})
)
);
});
示例13: describe
describe('SummaryService', () => {
let summaryService: SummaryService;
let authStorageService: AuthStorageService;
const summary = {
executing_tasks: [],
health_status: 'HEALTH_OK',
mgr_id: 'x',
rbd_mirroring: { errors: 0, warnings: 0 },
rbd_pools: [],
have_mon_connection: true,
finished_tasks: [],
filesystems: [{ id: 1, name: 'cephfs_a' }]
};
const httpClientSpy = {
get: () => observableOf(summary)
};
configureTestBed({
imports: [RouterTestingModule],
providers: [
SummaryService,
AuthStorageService,
{ provide: HttpClient, useValue: httpClientSpy }
]
});
beforeEach(() => {
summaryService = TestBed.get(SummaryService);
authStorageService = TestBed.get(AuthStorageService);
});
it('should be created', () => {
expect(summaryService).toBeTruthy();
});
it('should call refresh', fakeAsync(() => {
authStorageService.set('foobar', undefined, undefined);
const calledWith = [];
summaryService.subscribe((data) => {
calledWith.push(data);
});
expect(calledWith).toEqual([summary]);
summaryService.refresh();
expect(calledWith).toEqual([summary, summary]);
tick(10000);
expect(calledWith.length).toEqual(4);
// In order to not trigger setTimeout again,
// which would raise 'Error: 1 timer(s) still in the queue.'
spyOn(summaryService, 'refresh').and.callFake(() => true);
tick(5000);
}));
describe('Should test methods after first refresh', () => {
beforeEach(() => {
authStorageService.set('foobar', undefined, undefined);
summaryService.refresh();
});
it('should call getCurrentSummary', () => {
expect(summaryService.getCurrentSummary()).toEqual(summary);
});
it('should call subscribe', () => {
let result;
const subscriber = summaryService.subscribe((data) => {
result = data;
});
expect(subscriber).toEqual(jasmine.any(Subscriber));
expect(result).toEqual(summary);
});
it('should call addRunningTask', () => {
summaryService.addRunningTask(
new ExecutingTask('rbd/delete', {
pool_name: 'somePool',
image_name: 'someImage'
})
);
const result = summaryService.getCurrentSummary();
expect(result.executing_tasks.length).toBe(1);
expect(result.executing_tasks[0]).toEqual({
metadata: { image_name: 'someImage', pool_name: 'somePool' },
name: 'rbd/delete'
});
});
it('should call addRunningTask with duplicate task', () => {
let result = summaryService.getCurrentSummary();
const exec_task = new ExecutingTask('rbd/delete', {
pool_name: 'somePool',
image_name: 'someImage'
});
result.executing_tasks = [exec_task];
summaryService['summaryDataSource'].next(result);
result = summaryService.getCurrentSummary();
expect(result.executing_tasks.length).toBe(1);
//.........这里部分代码省略.........
示例14: describe
describe('observables', () => {
function observableValidator(response: {[key: string]: any}): AsyncValidatorFn {
return (c: AbstractControl) => {
const res = c.value != 'expected' ? response : null;
return of (res);
};
}
it('should return null when given null',
() => { expect(Validators.composeAsync(null !)).toBeNull(); });
it('should collect errors from all the validators', () => {
const v = Validators.composeAsync(
[observableValidator({'one': true}), observableValidator({'two': true})]) !;
let errorMap: {[key: string]: any} = undefined !;
first.call(v(new FormControl('invalid')))
.subscribe((errors: {[key: string]: any}) => errorMap = errors);
expect(errorMap).toEqual({'one': true, 'two': true});
});
it('should normalize and evaluate async validator-directives correctly', () => {
const v = Validators.composeAsync(
[normalizeAsyncValidator(new AsyncValidatorDirective('expected', {'one': true}))]) !;
let errorMap: {[key: string]: any} = undefined !;
first.call(v(new FormControl('invalid')))
.subscribe((errors: {[key: string]: any}) => errorMap = errors) !;
expect(errorMap).toEqual({'one': true});
});
it('should return null when no errors', () => {
const v = Validators.composeAsync([observableValidator({'one': true})]) !;
let errorMap: {[key: string]: any} = undefined !;
first.call(v(new FormControl('expected')))
.subscribe((errors: {[key: string]: any}) => errorMap = errors);
expect(errorMap).toBeNull();
});
it('should ignore nulls', () => {
const v = Validators.composeAsync([observableValidator({'one': true}), null !]) !;
let errorMap: {[key: string]: any} = undefined !;
first.call(v(new FormControl('invalid')))
.subscribe((errors: {[key: string]: any}) => errorMap = errors);
expect(errorMap).toEqual({'one': true});
});
it('should wait for all validators before setting errors', fakeAsync(() => {
function getTimerObs(time: number, errorMap: {[key: string]: any}): AsyncValidatorFn {
return (c: AbstractControl) => { return map.call(timer(time), () => errorMap); };
}
const v = Validators.composeAsync(
[getTimerObs(100, {one: true}), getTimerObs(200, {two: true})]) !;
let errorMap: {[key: string]: any} = undefined !;
first.call(v(new FormControl('invalid')))
.subscribe((errors: {[key: string]: any}) => errorMap = errors);
tick(100);
expect(errorMap).not.toBeDefined(
`Expected errors not to be set until all validators came back.`);
tick(100);
expect(errorMap).toEqual(
{one: true, two: true}, `Expected errors to merge once all validators resolved.`);
}));
});
示例15: describe
describe('ModuleStatusGuardService', () => {
let service: ModuleStatusGuardService;
@Component({ selector: 'cd-foo', template: '' })
class FooComponent {}
const fakeService = {
get: () => true
};
const routes: Routes = [{ path: '**', component: FooComponent }];
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(routes)],
providers: [ModuleStatusGuardService, { provide: HttpClient, useValue: fakeService }],
declarations: [FooComponent]
});
service = TestBed.get(ModuleStatusGuardService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it(
'should test canActivate with status available',
fakeAsync(() => {
let result = false;
const route = new ActivatedRouteSnapshot();
route.data = {
moduleStatusGuardConfig: {
apiPath: 'bar',
redirectTo: 'foo'
}
};
const httpClient = TestBed.get(HttpClient);
spyOn(httpClient, 'get').and.returnValue(observableOf({ available: true, message: 'foo' }));
service.canActivate(route, null).subscribe((resp) => {
result = resp;
});
tick();
expect(result).toBe(true);
})
);
it(
'should test canActivateChild with status unavailable',
fakeAsync(() => {
let result = true;
const route = new ActivatedRouteSnapshot();
route.data = {
moduleStatusGuardConfig: {
apiPath: 'bar',
redirectTo: '/foo'
}
};
const httpClient = TestBed.get(HttpClient);
const router = TestBed.get(Router);
spyOn(httpClient, 'get').and.returnValue(observableOf({ available: false, message: null }));
service.canActivateChild(route, null).subscribe((resp) => {
result = resp;
});
tick();
expect(result).toBe(false);
expect(router.url).toBe('/foo/');
})
);
it(
'should test canActivateChild with status unavailable',
fakeAsync(() => {
let result = true;
const route = new ActivatedRouteSnapshot();
route.data = {
moduleStatusGuardConfig: {
apiPath: 'bar',
redirectTo: '/foo'
}
};
const httpClient = TestBed.get(HttpClient);
const router = TestBed.get(Router);
spyOn(httpClient, 'get').and.returnValue(observableOf(null));
service.canActivateChild(route, null).subscribe((resp) => {
result = resp;
});
tick();
expect(result).toBe(false);
expect(router.url).toBe('/foo');
})
);
});