_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/zone.js/test/browser/define-property.spec.ts_0_4810 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
describe('defineProperty', function () {
it('should not throw when defining length on an array', function () {
const someArray: any[] = [];
expect(() =>
Object.defineProperty(someArray, 'length', {value: 2, writable: false}),
).not.toThrow();
});
it('should not be able to change a frozen desc', function () {
const obj = {};
const desc = Object.freeze({value: null, writable: true});
Object.defineProperty(obj, 'prop', desc);
let objDesc: any = Object.getOwnPropertyDescriptor(obj, 'prop');
expect(objDesc.writable).toBeTruthy();
try {
Object.defineProperty(obj, 'prop', {configurable: true, writable: true, value: 'test'});
} catch (err) {}
objDesc = Object.getOwnPropertyDescriptor(obj, 'prop');
expect(objDesc.configurable).toBeFalsy();
});
it('should not throw error when try to defineProperty with a frozen obj', function () {
const obj = {};
Object.freeze(obj);
try {
Object.defineProperty(obj, 'prop', {configurable: true, writable: true, value: 'value'});
} catch (err) {}
expect((obj as any).prop).toBeFalsy();
});
});
describe('defineProperties', () => {
it('should set string props', () => {
const obj: any = {};
Object.defineProperties(obj, {
'property1': {value: true, writable: true, enumerable: true},
'property2': {value: 'Hello', writable: false, enumerable: true},
'property3': {
enumerable: true,
get: () => {
return obj.p3;
},
set: (val: string) => (obj.p3 = val),
},
'property4': {enumerable: false, writable: true, value: 'hidden'},
});
expect(Object.keys(obj).sort()).toEqual(['property1', 'property2', 'property3']);
expect(obj.property1).toBeTrue();
expect(obj.property2).toEqual('Hello');
expect(obj.property3).toBeUndefined();
expect(obj.property4).toEqual('hidden');
obj.property1 = false;
expect(obj.property1).toBeFalse();
expect(() => (obj.property2 = 'new Hello')).toThrow();
obj.property3 = 'property3';
expect(obj.property3).toEqual('property3');
obj.property4 = 'property4';
expect(obj.property4).toEqual('property4');
});
it('should set symbol props', () => {
let a = Symbol();
let b = Symbol();
const obj: any = {};
Object.defineProperties(obj, {
[a]: {value: true, writable: true},
[b]: {get: () => obj.b1, set: (val: string) => (obj.b1 = val)},
});
expect(Object.keys(obj)).toEqual([]);
expect(obj[a]).toBeTrue();
expect(obj[b]).toBeUndefined();
obj[a] = false;
expect(obj[a]).toBeFalse();
obj[b] = 'b1';
expect(obj[b]).toEqual('b1');
});
it('should set string and symbol props', () => {
let a = Symbol();
const obj: any = {};
Object.defineProperties(obj, {
[a]: {value: true, writable: true},
'property1': {value: true, writable: true, enumerable: true},
});
expect(Object.keys(obj)).toEqual(['property1']);
expect(obj.property1).toBeTrue();
expect(obj[a]).toBeTrue();
obj.property1 = false;
expect(obj.property1).toBeFalse();
obj[a] = false;
expect(obj[a]).toBeFalse();
});
it('should only set enumerable symbol props', () => {
let a = Symbol();
// Create a props object contains 2 symbols properties.
// 1. Symbol a, the value is a PropertyDescriptor and enumerable is true.
// 2. builtin Symbol.hasInstance, the value is a PropertyDescriptor and enumerable is false.
// When set the props to the Test class with Object.defineProperties, only the enumerable props
// should be set, so Symbol.hasInstance should not be set, and `instanceof Test` should not
// throw error.
const props = {};
Object.defineProperty(props, a, {
value: {
value: true,
configurable: true,
writable: true,
enumerable: true,
},
configurable: true,
writable: true,
enumerable: true,
});
Object.defineProperty(props, Symbol.hasInstance, {
value: {
value: () => {
throw new Error('Cannot perform instanceof checks');
},
configurable: false,
writable: false,
enumerable: false,
},
configurable: false,
writable: false,
enumerable: false,
});
class Test {}
const obj = new Test();
Object.defineProperties(Test, props);
expect(Object.keys(obj)).toEqual([]);
expect((Test as any)[a]).toBeTrue();
(Test as any)[a] = false;
expect((Test as any)[a]).toBeFalse();
expect(obj instanceof Test).toBeTrue();
});
});
| {
"end_byte": 4810,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/define-property.spec.ts"
} |
angular/packages/zone.js/test/browser/WebSocket.spec.ts_0_4129 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
declare const window: any;
const TIMEOUT = 5000;
if (!window['saucelabs']) {
// sauceLabs does not support WebSockets; skip these tests
xdescribe(
'WebSocket',
ifEnvSupports('WebSocket', function () {
let socket: WebSocket;
const TEST_SERVER_URL = 'ws://localhost:8001';
const testZone = Zone.current.fork({name: 'test'});
beforeEach(function (done) {
socket = new WebSocket(TEST_SERVER_URL);
socket.addEventListener('open', function () {
done();
});
socket.addEventListener('error', function () {
fail(
"Can't establish socket to " +
TEST_SERVER_URL +
'! do you have test/ws-server.js running?',
);
done();
});
}, TIMEOUT);
afterEach(function (done) {
socket.addEventListener('close', function () {
done();
});
socket.close();
}, TIMEOUT);
xit('should be patched in a Web Worker', (done) => {
const worker = new Worker('/base/test/ws-webworker-context.js');
worker.onmessage = (e: MessageEvent) => {
if (e.data !== 'pass' && e.data !== 'fail') {
fail(`web worker ${e.data}`);
return;
}
expect(e.data).toBe('pass');
done();
};
}, 10000);
it(
'should work with addEventListener',
function (done) {
testZone.run(function () {
socket.addEventListener('message', function (event) {
expect(Zone.current).toBe(testZone);
expect(event['data']).toBe('hi');
done();
});
});
socket.send('hi');
},
TIMEOUT,
);
it(
'should respect removeEventListener',
function (done) {
let log = '';
function logOnMessage() {
log += 'a';
expect(log).toEqual('a');
socket.removeEventListener('message', logOnMessage);
socket.send('hi');
setTimeout(function () {
expect(log).toEqual('a');
done();
}, 10);
}
socket.addEventListener('message', logOnMessage);
socket.send('hi');
},
TIMEOUT,
);
it(
'should work with onmessage',
function (done) {
testZone.run(function () {
socket.onmessage = function (contents) {
expect(Zone.current).toBe(testZone);
expect(contents.data).toBe('hi');
done();
};
});
socket.send('hi');
},
TIMEOUT,
);
it(
'should only allow one onmessage handler',
function (done) {
let log = '';
socket.onmessage = function () {
log += 'a';
expect(log).toEqual('b');
done();
};
socket.onmessage = function () {
log += 'b';
expect(log).toEqual('b');
done();
};
socket.send('hi');
},
TIMEOUT,
);
it(
'should handler removing onmessage',
function (done) {
let log = '';
socket.onmessage = function () {
log += 'a';
};
socket.onmessage = null as any;
socket.send('hi');
setTimeout(function () {
expect(log).toEqual('');
done();
}, 100);
},
TIMEOUT,
);
it('should have constants', function () {
expect(Object.keys(WebSocket)).toContain('CONNECTING');
expect(Object.keys(WebSocket)).toContain('OPEN');
expect(Object.keys(WebSocket)).toContain('CLOSING');
expect(Object.keys(WebSocket)).toContain('CLOSED');
});
}),
);
}
| {
"end_byte": 4129,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/WebSocket.spec.ts"
} |
angular/packages/zone.js/test/browser/custom-element.spec.js_0_3541 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/*
* check that document.registerElement(name, { prototype: proto });
* is properly patched
*/
function customElementsSupport() {
return 'registerElement' in document;
}
customElementsSupport.message = 'window.customElements';
function supportsFormAssociatedElements() {
return 'attachInternals' in HTMLElement.prototype;
}
describe('customElements', function () {
const testZone = Zone.current.fork({name: 'test'});
const bridge = {
connectedCallback: () => {},
disconnectedCallback: () => {},
adoptedCallback: () => {},
attributeChangedCallback: () => {},
formAssociatedCallback: () => {},
};
class TestCustomElement extends HTMLElement {
constructor() {
super();
}
static get observedAttributes() {
return ['attr1', 'attr2'];
}
connectedCallback() {
return bridge.connectedCallback();
}
disconnectedCallback() {
return bridge.disconnectedCallback();
}
attributeChangedCallback(attrName, oldVal, newVal) {
return bridge.attributeChangedCallback(attrName, oldVal, newVal);
}
adoptedCallback() {
return bridge.adoptedCallback();
}
}
class TestFormAssociatedCustomElement extends HTMLElement {
static formAssociated = true;
formAssociatedCallback() {
return bridge.formAssociatedCallback();
}
}
testZone.run(() => {
customElements.define('x-test', TestCustomElement);
customElements.define('x-test-form-associated', TestFormAssociatedCustomElement);
});
let elt;
beforeEach(() => {
bridge.connectedCallback = () => {};
bridge.disconnectedCallback = () => {};
bridge.attributeChangedCallback = () => {};
bridge.adoptedCallback = () => {};
bridge.formAssociatedCallback = () => {};
});
afterEach(() => {
if (elt) {
document.body.removeChild(elt);
elt = null;
}
});
it('should work with connectedCallback', function (done) {
bridge.connectedCallback = function () {
expect(Zone.current.name).toBe(testZone.name);
done();
};
elt = document.createElement('x-test');
document.body.appendChild(elt);
});
it('should work with disconnectedCallback', function (done) {
bridge.disconnectedCallback = function () {
expect(Zone.current.name).toBe(testZone.name);
done();
};
elt = document.createElement('x-test');
document.body.appendChild(elt);
document.body.removeChild(elt);
elt = null;
});
it('should work with attributeChanged', function (done) {
bridge.attributeChangedCallback = function (attrName, oldVal, newVal) {
expect(Zone.current.name).toBe(testZone.name);
expect(attrName).toEqual('attr1');
expect(newVal).toEqual('value1');
done();
};
elt = document.createElement('x-test');
document.body.appendChild(elt);
elt.setAttribute('attr1', 'value1');
});
it('should work with formAssociatedCallback', function (done) {
if (!supportsFormAssociatedElements()) {
return;
}
bridge.formAssociatedCallback = function () {
expect(Zone.current.name).toBe(testZone.name);
done();
};
elt = document.createElement('x-test-form-associated');
const form = document.createElement('form');
form.appendChild(elt);
document.body.appendChild(form);
});
});
| {
"end_byte": 3541,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/custom-element.spec.js"
} |
angular/packages/zone.js/test/browser/MutationObserver.spec.ts_0_2152 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
declare const global: any;
describe(
'MutationObserver',
ifEnvSupports('MutationObserver', function () {
let elt: HTMLDivElement;
beforeEach(function () {
elt = document.createElement('div');
document.body.appendChild(elt);
});
afterEach(function () {
document.body.removeChild(elt);
});
it('should run observers within the zone', function (done) {
const testZone = Zone.current.fork({name: 'test'});
let ob;
elt = document.createElement('div');
document.body.appendChild(elt);
testZone.run(function () {
ob = new MutationObserver(function () {
expect(Zone.current).toBe(testZone);
done();
});
ob.observe(elt, {childList: true});
});
elt.innerHTML = '<p>hey</p>';
});
it('should only dequeue upon disconnect if something is observed', function () {
let ob: MutationObserver;
let flag = false;
const elt = document.createElement('div');
const childZone = Zone.current.fork({
name: 'test',
onInvokeTask: function () {
flag = true;
},
});
childZone.run(function () {
ob = new MutationObserver(function () {});
});
ob!.disconnect();
expect(flag).toBe(false);
});
}),
);
describe(
'WebKitMutationObserver',
ifEnvSupports('WebKitMutationObserver', function () {
it('should run observers within the zone', function (done) {
const testZone = Zone.current.fork({name: 'test'});
let elt: HTMLDivElement;
testZone.run(function () {
elt = document.createElement('div');
const ob = new global['WebKitMutationObserver'](function () {
expect(Zone.current).toBe(testZone);
done();
});
ob.observe(elt, {childList: true});
});
elt!.innerHTML = '<p>hey</p>';
});
}),
);
| {
"end_byte": 2152,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/MutationObserver.spec.ts"
} |
angular/packages/zone.js/test/browser/Worker.spec.ts_0_1222 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {zoneSymbol} from '../../lib/common/utils';
import {asyncTest, ifEnvSupports} from '../test-util';
function workerSupport() {
const Worker = (window as any)['Worker'];
if (!Worker) {
return false;
}
const desc = Object.getOwnPropertyDescriptor(Worker.prototype, 'onmessage');
if (!desc || !desc.configurable) {
return false;
}
return true;
}
(workerSupport as any).message = 'Worker Support';
xdescribe(
'Worker API',
ifEnvSupports(workerSupport, function () {
it(
'Worker API should be patched by Zone',
asyncTest((done: Function) => {
const zone: Zone = Zone.current.fork({name: 'worker'});
zone.run(() => {
const worker = new Worker('/base/angular/packages/zone.js/test/assets/worker.js');
worker.onmessage = function (evt: MessageEvent) {
expect(evt.data).toEqual('worker');
expect(Zone.current.name).toEqual('worker');
done();
};
});
}, Zone.root),
);
}),
);
| {
"end_byte": 1222,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/Worker.spec.ts"
} |
angular/packages/zone.js/test/browser/FileReader.spec.ts_0_3408 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
declare const global: any;
describe(
'FileReader',
ifEnvSupports('FileReader', function () {
let fileReader: FileReader;
let blob: Blob;
const data = 'Hello, World!';
// Android 4.3's native browser doesn't implement add/RemoveEventListener for FileReader
function supportsEventTargetFns() {
return !!FileReader.prototype.addEventListener && !!FileReader.prototype.removeEventListener;
}
(<any>supportsEventTargetFns).message =
'FileReader#addEventListener and FileReader#removeEventListener';
beforeEach(function () {
fileReader = new FileReader();
try {
blob = new Blob([data]);
} catch (e) {
// For hosts that don't support the Blob ctor (e.g. Android 4.3's native browser)
const blobBuilder = new global['WebKitBlobBuilder']();
blobBuilder.append(data);
blob = blobBuilder.getBlob();
}
});
describe(
'EventTarget methods',
ifEnvSupports(supportsEventTargetFns, function () {
it('should bind addEventListener listeners', function (done) {
const testZone = Zone.current.fork({name: 'TestZone'});
testZone.run(function () {
fileReader.addEventListener('load', function () {
expect(Zone.current).toBe(testZone);
expect(fileReader.result).toEqual(data);
done();
});
});
fileReader.readAsText(blob);
});
it('should remove listeners via removeEventListener', function (done) {
const testZone = Zone.current.fork({name: 'TestZone'});
const listenerSpy = jasmine.createSpy('listener');
testZone.run(function () {
fileReader.addEventListener('loadstart', listenerSpy);
fileReader.addEventListener('loadend', function () {
expect(listenerSpy).not.toHaveBeenCalled();
done();
});
});
fileReader.removeEventListener('loadstart', listenerSpy);
fileReader.readAsText(blob);
});
}),
);
it('should bind onEventType listeners', function (done) {
const testZone = Zone.current.fork({name: 'TestZone'});
let listenersCalled = 0;
testZone.run(function () {
fileReader.onloadstart = function () {
listenersCalled++;
expect(Zone.current).toBe(testZone);
};
fileReader.onload = function () {
listenersCalled++;
expect(Zone.current).toBe(testZone);
};
fileReader.onloadend = function () {
listenersCalled++;
expect(Zone.current).toBe(testZone);
expect(fileReader.result).toEqual(data);
expect(listenersCalled).toBe(3);
done();
};
});
fileReader.readAsText(blob);
});
it('should have correct readyState', function (done) {
fileReader.onloadend = function () {
expect(fileReader.readyState).toBe((<any>FileReader).DONE);
done();
};
expect(fileReader.readyState).toBe((<any>FileReader).EMPTY);
fileReader.readAsText(blob);
});
}),
);
| {
"end_byte": 3408,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/FileReader.spec.ts"
} |
angular/packages/zone.js/test/browser/HTMLImports.spec.ts_0_2292 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
function supportsImports() {
return 'import' in document.createElement('link');
}
if (supportsImports()) {
describe('HTML Imports', function () {
const testZone = Zone.current.fork({name: 'test'});
it('should work with addEventListener', function (done) {
let link: HTMLLinkElement;
testZone.run(function () {
link = document.createElement('link');
link.rel = 'import';
link.href = 'someUrl';
link.addEventListener('error', function () {
expect(Zone.current).toBe(testZone);
document.head.removeChild(link);
done();
});
});
document.head.appendChild(link!);
});
function supportsOnEvents() {
const link = document.createElement('link');
const linkPropDesc = Object.getOwnPropertyDescriptor(link, 'onerror');
return !(linkPropDesc && linkPropDesc.value === null);
}
(<any>supportsOnEvents).message = 'Supports HTMLLinkElement#onxxx patching';
ifEnvSupports(supportsOnEvents, function () {
it('should work with onerror', function (done) {
let link: HTMLLinkElement;
testZone.run(function () {
link = document.createElement('link');
link.rel = 'import';
link.href = 'anotherUrl';
link.onerror = function () {
expect(Zone.current).toBe(testZone);
document.head.removeChild(link);
done();
};
});
document.head.appendChild(link!);
});
it('should work with onload', function (done) {
let link: HTMLLinkElement;
testZone.run(function () {
link = document.createElement('link');
link.rel = 'import';
link.href = '/base/angular/packages/zone.js/test/assets/import.html';
link.onload = function () {
expect(Zone.current).toBe(testZone);
document.head.removeChild(link);
done();
};
});
document.head.appendChild(link!);
});
});
});
}
| {
"end_byte": 2292,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/HTMLImports.spec.ts"
} |
angular/packages/zone.js/test/browser/element.spec.ts_0_8125 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
describe('element', function () {
let button: HTMLButtonElement;
beforeEach(function () {
button = document.createElement('button');
document.body.appendChild(button);
});
afterEach(function () {
document.body.removeChild(button);
});
// https://github.com/angular/zone.js/issues/190
it('should work when addEventListener / removeEventListener are called in the global context', function () {
const clickEvent = document.createEvent('Event');
let callCount = 0;
clickEvent.initEvent('click', true, true);
const listener = function (event: Event) {
callCount++;
expect(event).toBe(clickEvent);
};
// `this` would be null inside the method when `addEventListener` is called from strict mode
// it would be `window`:
// - when called from non strict-mode,
// - when `window.addEventListener` is called explicitly.
addEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
});
it('should work with addEventListener when called with a function listener', function () {
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.addEventListener('click', function (event) {
expect(event).toBe(clickEvent as any);
});
button.dispatchEvent(clickEvent);
});
it('should not call microtasks early when an event is invoked', function (done) {
let log = '';
button.addEventListener('click', () => {
Zone.current.scheduleMicroTask('test', () => (log += 'microtask;'));
log += 'click;';
});
button.click();
expect(log).toEqual('click;');
done();
});
it('should call microtasks early when an event is invoked', function (done) {
/*
* In this test we escape the Zone using unpatched setTimeout.
* This way the eventTask invoked from click will think it is the top most
* task and eagerly drain the microtask queue.
*
* THIS IS THE WRONG BEHAVIOR!
*
* But there is no easy way for the task to know if it is the top most task.
*
* Given that this can only arise when someone is emulating clicks on DOM in a synchronous
* fashion we have few choices:
* 1. Ignore as this is unlikely to be a problem outside of tests.
* 2. Monkey patch the event methods to increment the _numberOfNestedTaskFrames and prevent
* eager drainage.
* 3. Pay the cost of throwing an exception in event tasks and verifying that we are the
* top most frame.
*
* For now we are choosing to ignore it and assume that this arises in tests only.
* As an added measure we make sure that all jasmine tests always run in a task. See: jasmine.ts
*/
(window as any)[(Zone as any).__symbol__('setTimeout')](() => {
let log = '';
button.addEventListener('click', () => {
Zone.current.scheduleMicroTask('test', () => (log += 'microtask;'));
log += 'click;';
});
button.click();
expect(log).toEqual('click;microtask;');
done();
});
});
it('should work with addEventListener when called with an EventListener-implementing listener', function () {
const eventListener = {
x: 5,
handleEvent: function (event: Event) {
// Test that context is preserved
expect(this.x).toBe(5);
expect(event).toBe(clickEvent);
},
};
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.addEventListener('click', eventListener);
button.dispatchEvent(clickEvent);
});
it('should respect removeEventListener when called with a function listener', function () {
let log = '';
const logFunction = function logFunction() {
log += 'a';
};
button.addEventListener('click', logFunction);
button.addEventListener('focus', logFunction);
button.click();
expect(log).toEqual('a');
const focusEvent = document.createEvent('Event');
focusEvent.initEvent('focus', true, true);
button.dispatchEvent(focusEvent);
expect(log).toEqual('aa');
button.removeEventListener('click', logFunction);
button.click();
expect(log).toEqual('aa');
});
it('should respect removeEventListener with an EventListener-implementing listener', function () {
const eventListener = {x: 5, handleEvent: jasmine.createSpy('handleEvent')};
button.addEventListener('click', eventListener);
button.removeEventListener('click', eventListener);
button.click();
expect(eventListener.handleEvent).not.toHaveBeenCalled();
});
it('should have no effect while calling addEventListener without listener', function () {
const onAddEventListenerSpy = jasmine.createSpy('addEventListener');
const eventListenerZone = Zone.current.fork({
name: 'eventListenerZone',
onScheduleTask: onAddEventListenerSpy,
});
expect(function () {
eventListenerZone.run(function () {
button.addEventListener('click', null as any);
button.addEventListener('click', undefined as any);
});
}).not.toThrowError();
expect(onAddEventListenerSpy).not.toHaveBeenCalledWith();
});
it('should have no effect while calling removeEventListener without listener', function () {
const onAddEventListenerSpy = jasmine.createSpy('removeEventListener');
const eventListenerZone = Zone.current.fork({
name: 'eventListenerZone',
onScheduleTask: onAddEventListenerSpy,
});
expect(function () {
eventListenerZone.run(function () {
button.removeEventListener('click', null as any);
button.removeEventListener('click', undefined as any);
});
}).not.toThrowError();
expect(onAddEventListenerSpy).not.toHaveBeenCalledWith();
});
it('should only add a listener once for a given set of arguments', function () {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
function listener() {
log.push('listener');
}
clickEvent.initEvent('click', true, true);
button.addEventListener('click', listener);
button.addEventListener('click', listener);
button.addEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['listener']);
button.removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['listener']);
});
it('should correctly handler capturing versus nonCapturing eventListeners', function () {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
function capturingListener() {
log.push('capturingListener');
}
function bubblingListener() {
log.push('bubblingListener');
}
clickEvent.initEvent('click', true, true);
document.body.addEventListener('click', capturingListener, true);
document.body.addEventListener('click', bubblingListener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['capturingListener', 'bubblingListener']);
});
it('should correctly handler a listener that is both capturing and nonCapturing', function () {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
function listener() {
log.push('listener');
}
clickEvent.initEvent('click', true, true);
document.body.addEventListener('click', listener, true);
document.body.addEventListener('click', listener);
button.dispatchEvent(clickEvent);
document.body.removeEventListener('click', listener, true);
document.body.removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['listener', 'listener']);
}); | {
"end_byte": 8125,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/element.spec.ts"
} |
angular/packages/zone.js/test/browser/element.spec.ts_8129_10473 | describe('onclick', function () {
function supportsOnClick() {
const div = document.createElement('div');
const clickPropDesc = Object.getOwnPropertyDescriptor(div, 'onclick');
return !(
EventTarget &&
div instanceof EventTarget &&
clickPropDesc &&
clickPropDesc.value === null
);
}
(<any>supportsOnClick).message = 'Supports Element#onclick patching';
ifEnvSupports(supportsOnClick, function () {
it('should spawn new child zones', function () {
let run = false;
button.onclick = function () {
run = true;
};
button.click();
expect(run).toBeTruthy();
});
});
it('should only allow one onclick handler', function () {
let log = '';
button.onclick = function () {
log += 'a';
};
button.onclick = function () {
log += 'b';
};
button.click();
expect(log).toEqual('b');
});
it('should handler removing onclick', function () {
let log = '';
button.onclick = function () {
log += 'a';
};
button.onclick = null as any;
button.click();
expect(log).toEqual('');
});
it('should be able to deregister the same event twice', function () {
const listener = (event: Event) => {};
document.body.addEventListener('click', listener, false);
document.body.removeEventListener('click', listener, false);
document.body.removeEventListener('click', listener, false);
});
});
describe('onEvent default behavior', function () {
let checkbox: HTMLInputElement;
beforeEach(function () {
checkbox = document.createElement('input');
checkbox.type = 'checkbox';
document.body.appendChild(checkbox);
});
afterEach(function () {
document.body.removeChild(checkbox);
});
it('should be possible to prevent default behavior by returning false', function () {
checkbox.onclick = function () {
return false;
};
checkbox.click();
expect(checkbox.checked).toBe(false);
});
it('should have no effect on default behavior when not returning anything', function () {
checkbox.onclick = function () {};
checkbox.click();
expect(checkbox.checked).toBe(true);
});
});
}); | {
"end_byte": 10473,
"start_byte": 8129,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/element.spec.ts"
} |
angular/packages/zone.js/test/browser/Notification.spec.ts_0_945 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {zoneSymbol} from '../../lib/common/utils';
import {ifEnvSupports} from '../test-util';
declare const window: any;
function notificationSupport() {
const desc =
window['Notification'] &&
Object.getOwnPropertyDescriptor(window['Notification'].prototype, 'onerror');
return window['Notification'] && window['Notification'].prototype && desc && desc.configurable;
}
(<any>notificationSupport).message = 'Notification Support';
describe(
'Notification API',
ifEnvSupports(notificationSupport, function () {
it('Notification API should be patched by Zone', () => {
const Notification = window['Notification'];
expect(Notification.prototype[zoneSymbol('addEventListener')]).toBeTruthy();
});
}),
);
| {
"end_byte": 945,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/Notification.spec.ts"
} |
angular/packages/zone.js/test/browser/messageport.spec.ts_0_1402 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Test MessagePort monkey patch.
*/
describe('MessagePort onproperties', () => {
let iframe: any;
beforeEach(() => {
iframe = document.createElement('iframe');
const html = `<body>
<script>
window.addEventListener('message', onMessage);
function onMessage(e) {
// Use the transferred port to post a message back to the main frame
e.ports[0].postMessage('Message back from the IFrame');
}
</script>
</body>`;
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
});
afterEach(() => {
if (iframe) {
document.body.removeChild(iframe);
}
});
it('onmessge should in the zone', (done) => {
const channel = new MessageChannel();
const zone = Zone.current.fork({name: 'zone'});
iframe.onload = function () {
zone.run(() => {
channel.port1.onmessage = function () {
expect(Zone.current.name).toBe(zone.name);
done();
};
Zone.current.fork({name: 'zone1'}).run(() => {
iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
});
});
};
document.body.appendChild(iframe);
});
});
| {
"end_byte": 1402,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/messageport.spec.ts"
} |
angular/packages/zone.js/test/browser/MediaQuery.spec.ts_0_868 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {zoneSymbol} from '../../lib/common/utils';
import {ifEnvSupports} from '../test-util';
declare const global: any;
function supportMediaQuery() {
const _global =
(typeof window === 'object' && window) || (typeof self === 'object' && self) || global;
return _global['MediaQueryList'] && _global['matchMedia'];
}
describe(
'test mediaQuery patch',
ifEnvSupports(supportMediaQuery, () => {
it('test whether addListener is patched', () => {
const mqList = window.matchMedia('min-width:500px');
if (mqList && mqList['addListener']) {
expect((mqList as any)[zoneSymbol('addListener')]).toBeTruthy();
}
});
}),
);
| {
"end_byte": 868,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/MediaQuery.spec.ts"
} |
angular/packages/zone.js/test/browser/geolocation.spec.manual.ts_0_1132 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
function supportsGeolocation() {
return 'geolocation' in navigator;
}
(<any>supportsGeolocation).message = 'Geolocation';
describe(
'Geolocation',
ifEnvSupports(supportsGeolocation, function () {
const testZone = Zone.current.fork({name: 'geotest'});
it('should work for getCurrentPosition', function (done) {
testZone.run(function () {
navigator.geolocation.getCurrentPosition(function (pos) {
expect(Zone.current).toBe(testZone);
done();
});
});
}, 10000);
it('should work for watchPosition', function (done) {
testZone.run(function () {
let watchId: number;
watchId = navigator.geolocation.watchPosition(function (pos) {
expect(Zone.current).toBe(testZone);
navigator.geolocation.clearWatch(watchId);
done();
});
});
}, 10000);
}),
);
| {
"end_byte": 1132,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/browser/geolocation.spec.manual.ts"
} |
angular/packages/zone.js/test/common/microtasks.spec.ts_0_3078 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
describe('Microtasks', function () {
if (!global.Promise) return;
function scheduleFn(task: Task) {
Promise.resolve().then(<any>task.invoke);
}
it('should execute microtasks enqueued in the root zone', function (done) {
const log: number[] = [];
Zone.current.scheduleMicroTask('test', () => log.push(1), undefined, scheduleFn);
Zone.current.scheduleMicroTask('test', () => log.push(2), undefined, scheduleFn);
Zone.current.scheduleMicroTask('test', () => log.push(3), undefined, scheduleFn);
setTimeout(function () {
expect(log).toEqual([1, 2, 3]);
done();
}, 10);
});
it('should correctly scheduleMacroTask microtasks vs macrotasks', function (done) {
const log = ['+root'];
Zone.current.scheduleMicroTask('test', () => log.push('root.mit'), undefined, scheduleFn);
setTimeout(function () {
log.push('+mat1');
Zone.current.scheduleMicroTask('test', () => log.push('mat1.mit'), undefined, scheduleFn);
log.push('-mat1');
}, 10);
setTimeout(function () {
log.push('mat2');
}, 30);
setTimeout(function () {
expect(log).toEqual(['+root', '-root', 'root.mit', '+mat1', '-mat1', 'mat1.mit', 'mat2']);
done();
}, 40);
log.push('-root');
});
it('should execute Promise wrapCallback in the zone where they are scheduled', function (done) {
const resolvedPromise = Promise.resolve(null);
const testZone = Zone.current.fork({name: ''});
testZone.run(function () {
resolvedPromise.then(function () {
expect(Zone.current.name).toBe(testZone.name);
done();
});
});
});
it(
'should execute Promise wrapCallback in the zone where they are scheduled even if resolved ' +
'in different zone.',
function (done) {
let resolve: Function;
const promise = new Promise(function (rs) {
resolve = rs;
});
const testZone = Zone.current.fork({name: 'test'});
testZone.run(function () {
promise.then(function () {
expect(Zone.current).toBe(testZone);
done();
});
});
Zone.current.fork({name: 'test'}).run(function () {
resolve(null);
});
},
);
describe('Promise', function () {
it('should go through scheduleTask', function (done) {
let called = false;
const testZone = Zone.current.fork({
name: 'test',
onScheduleTask: function (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
task: Task,
): Task {
called = true;
delegate.scheduleTask(target, task);
return task;
},
});
testZone.run(function () {
Promise.resolve('value').then(function () {
expect(called).toEqual(true);
done();
});
});
});
});
});
| {
"end_byte": 3078,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/microtasks.spec.ts"
} |
angular/packages/zone.js/test/common/queue-microtask.spec.ts_0_1028 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ifEnvSupports} from '../test-util';
describe(
'queueMicrotask',
ifEnvSupports('queueMicrotask', function () {
it('callback in the queueMicrotask should be scheduled as microTask in the zone', (done: DoneFn) => {
const logs: string[] = [];
Zone.current
.fork({
name: 'queueMicrotask',
onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
logs.push(task.type);
logs.push(task.source);
return delegate.scheduleTask(target, task);
},
})
.run(() => {
queueMicrotask(() => {
expect(logs).toEqual(['microTask', 'queueMicrotask']);
expect(Zone.current.name).toEqual('queueMicrotask');
done();
});
});
});
}),
);
| {
"end_byte": 1028,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/queue-microtask.spec.ts"
} |
angular/packages/zone.js/test/common/util.spec.ts_0_7394 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {patchMethod, patchProperty, patchPrototype, zoneSymbol} from '../../lib/common/utils';
describe('utils', function () {
describe('patchMethod', () => {
it('should patch target where the method is defined', () => {
let args: any[] | undefined;
let self: any;
class Type {
method(..._args: any[]) {
args = _args;
self = this;
return 'OK';
}
}
const method = Type.prototype.method;
let delegateMethod: Function;
let delegateSymbol: string;
const instance = new Type();
expect(
patchMethod(instance, 'method', (delegate: Function, symbol: string, name: string) => {
expect(name).toEqual('method');
delegateMethod = delegate;
delegateSymbol = symbol;
return function (self, args) {
return delegate.apply(self, ['patch', args[0]]);
};
}),
).toBe(delegateMethod!);
expect(instance.method('a0')).toEqual('OK');
expect(args).toEqual(['patch', 'a0']);
expect(self).toBe(instance);
expect(delegateMethod!).toBe(method);
expect(delegateSymbol!).toEqual(zoneSymbol('method'));
expect((Type.prototype as any)[delegateSymbol!]).toBe(method);
});
it('should not double patch', () => {
const Type = function () {};
const method = (Type.prototype.method = function () {});
patchMethod(Type.prototype, 'method', (delegate) => {
return function (self, args: any[]) {
return delegate.apply(self, ['patch', ...args]);
};
});
const pMethod = Type.prototype.method;
expect(pMethod).not.toBe(method);
patchMethod(Type.prototype, 'method', (delegate) => {
return function (self, args) {
return delegate.apply(self, ['patch', ...args]);
};
});
expect(pMethod).toBe(Type.prototype.method);
});
it('should not patch property which is not configurable', () => {
const TestType = function () {};
const originalDefineProperty = (Object as any)[zoneSymbol('defineProperty')];
if (originalDefineProperty) {
originalDefineProperty(TestType.prototype, 'nonConfigurableProperty', {
configurable: false,
writable: true,
value: 'test',
});
} else {
Object.defineProperty(TestType.prototype, 'nonConfigurableProperty', {
configurable: false,
writable: true,
value: 'test',
});
}
patchProperty(TestType.prototype, 'nonConfigurableProperty');
const desc = Object.getOwnPropertyDescriptor(TestType.prototype, 'nonConfigurableProperty');
expect(desc!.writable).toBeTruthy();
expect(!desc!.get).toBeTruthy();
});
it('should patch target if it overrides a patched method', () => {
let args: any[] | undefined;
let childArgs: any[] | undefined;
let self: any;
let childSelf: any;
class Type {
method(..._args: any[]) {
args = _args;
self = this;
return 'OK';
}
}
class ChildType extends Type {
override method(..._args: any[]) {
childArgs = _args;
childSelf = this;
return 'ChildOK';
}
}
const method = Type.prototype.method;
const childMethod = ChildType.prototype.method;
let delegateMethod: Function;
let delegateSymbol: string;
let childDelegateMethod: Function;
let childDelegateSymbol: string;
const typeInstance = new Type();
const childTypeInstance = new ChildType();
expect(
patchMethod(
Type.prototype,
'method',
(delegate: Function, symbol: string, name: string) => {
expect(name).toEqual('method');
delegateMethod = delegate;
delegateSymbol = symbol;
return function (self, args) {
return delegate.apply(self, ['patch', args[0]]);
};
},
),
).toBe(delegateMethod!);
expect(
patchMethod(
ChildType.prototype,
'method',
(delegate: Function, symbol: string, name: string) => {
expect(name).toEqual('method');
childDelegateMethod = delegate;
childDelegateSymbol = symbol;
return function (self, args) {
return delegate.apply(self, ['child patch', args[0]]);
};
},
),
).toBe(childDelegateMethod!);
expect(typeInstance.method('a0')).toEqual('OK');
expect(childTypeInstance.method('a0')).toEqual('ChildOK');
expect(args).toEqual(['patch', 'a0']);
expect(childArgs).toEqual(['child patch', 'a0']);
expect(self).toBe(typeInstance);
expect(childSelf).toBe(childTypeInstance);
expect(delegateMethod!).toBe(method);
expect(childDelegateMethod!).toBe(childMethod);
expect(delegateSymbol!).toEqual(zoneSymbol('method'));
expect(childDelegateSymbol!).toEqual(zoneSymbol('method'));
expect((Type.prototype as any)[delegateSymbol!]).toBe(method);
expect((ChildType.prototype as any)[delegateSymbol!]).toBe(childMethod);
});
it('should not patch target if does not override a patched method', () => {
let args: any[] | undefined;
let self: any;
class Type {
method(..._args: any[]) {
args = _args;
self = this;
return 'OK';
}
}
class ChildType extends Type {}
const method = Type.prototype.method;
let delegateMethod: Function;
let delegateSymbol: string;
let childPatched = false;
const typeInstance = new Type();
const childTypeInstance = new ChildType();
expect(
patchMethod(
Type.prototype,
'method',
(delegate: Function, symbol: string, name: string) => {
expect(name).toEqual('method');
delegateMethod = delegate;
delegateSymbol = symbol;
return function (self, args) {
return delegate.apply(self, ['patch', args[0]]);
};
},
),
).toBe(delegateMethod!);
expect(
patchMethod(
ChildType.prototype,
'method',
(delegate: Function, symbol: string, name: string) => {
childPatched = true;
return function (self, args) {
return delegate.apply(self, ['child patch', args[0]]);
};
},
),
).toBe(delegateMethod!);
expect(childPatched).toBe(false);
expect(typeInstance.method('a0')).toEqual('OK');
expect(args).toEqual(['patch', 'a0']);
expect(self).toBe(typeInstance);
expect(delegateMethod!).toBe(method);
expect(delegateSymbol!).toEqual(zoneSymbol('method'));
expect((Type.prototype as any)[delegateSymbol!]).toBe(method);
expect(childTypeInstance.method('a0')).toEqual('OK');
expect(args).toEqual(['patch', 'a0']);
expect(self).toBe(childTypeInstance);
expect((ChildType.prototype as any)[delegateSymbol!]).toBe(method);
});
}); | {
"end_byte": 7394,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/util.spec.ts"
} |
angular/packages/zone.js/test/common/util.spec.ts_7398_14848 | describe('patchPrototype', () => {
it('non configurable property desc should be patched', () => {
'use strict';
const TestFunction: any = function () {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property1': {
value: function Property1(callback: Function) {
Zone.root.run(callback);
},
writable: true,
configurable: true,
enumerable: true,
},
'property2': {
value: function Property2(callback: Function) {
Zone.root.run(callback);
},
writable: true,
configurable: false,
enumerable: true,
},
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1<root>', 'property2<root>']);
log.length = 0;
patchPrototype(TestFunction.prototype, ['property1', 'property2']);
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1patch', 'property2patch']);
});
it('non writable property desc should not be patched', () => {
'use strict';
const TestFunction: any = function () {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property1': {
value: function Property1(callback: Function) {
Zone.root.run(callback);
},
writable: true,
configurable: true,
enumerable: true,
},
'property2': {
value: function Property2(callback: Function) {
Zone.root.run(callback);
},
writable: false,
configurable: true,
enumerable: true,
},
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1<root>', 'property2<root>']);
log.length = 0;
patchPrototype(TestFunction.prototype, ['property1', 'property2']);
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1patch', 'property2<root>']);
});
it('readonly property desc should not be patched', () => {
'use strict';
const TestFunction: any = function () {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property1': {
get: function () {
if (!this._property1) {
this._property1 = function Property2(callback: Function) {
Zone.root.run(callback);
};
}
return this._property1;
},
set: function (func: Function) {
this._property1 = func;
},
configurable: true,
enumerable: true,
},
'property2': {
get: function () {
return function Property2(callback: Function) {
Zone.root.run(callback);
};
},
configurable: true,
enumerable: true,
},
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1<root>', 'property2<root>']);
log.length = 0;
patchPrototype(TestFunction.prototype, ['property1', 'property2']);
zone.run(() => {
const instance = new TestFunction();
instance.property1(() => {
log.push('property1' + Zone.current.name);
});
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property1patch', 'property2<root>']);
});
it('non writable method should not be patched', () => {
'use strict';
const TestFunction: any = function () {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property2': {
value: function Property2(callback: Function) {
Zone.root.run(callback);
},
writable: false,
configurable: true,
enumerable: true,
},
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
log.length = 0;
patchMethod(
TestFunction.prototype,
'property2',
function (delegate: Function, delegateName: string, name: string) {
return function (self: any, args: any) {
log.push('patched property2');
};
},
);
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
});
it('readonly method should not be patched', () => {
'use strict';
const TestFunction: any = function () {};
const log: string[] = [];
Object.defineProperties(TestFunction.prototype, {
'property2': {
get: function () {
return function Property2(callback: Function) {
Zone.root.run(callback);
};
},
configurable: true,
enumerable: true,
},
});
const zone = Zone.current.fork({name: 'patch'});
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
log.length = 0;
patchMethod(
TestFunction.prototype,
'property2',
function (delegate: Function, delegateName: string, name: string) {
return function (self: any, args: any) {
log.push('patched property2');
};
},
);
zone.run(() => {
const instance = new TestFunction();
instance.property2(() => {
log.push('property2' + Zone.current.name);
});
});
expect(log).toEqual(['property2<root>']);
});
});
}); | {
"end_byte": 14848,
"start_byte": 7398,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/util.spec.ts"
} |
angular/packages/zone.js/test/common/setInterval.spec.ts_0_3605 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
'use strict';
import {isNode, zoneSymbol} from '../../lib/common/utils';
declare const global: any;
const wtfMock = global.wtfMock;
describe('setInterval', function () {
it('should work with setInterval', function (done) {
let cancelId: any;
const testZone = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({name: 'TestZone'});
testZone.run(
() => {
let intervalCount = 0;
let timeoutRunning = false;
const intervalFn = function () {
intervalCount++;
expect(Zone.current.name).toEqual('TestZone');
if (timeoutRunning) {
return;
}
timeoutRunning = true;
global[zoneSymbol('setTimeout')](function () {
const intervalUnitLog = [
'> Zone:invokeTask:setInterval("<root>::ProxyZone::WTF::TestZone")',
'< Zone:invokeTask:setInterval',
];
let intervalLog: string[] = [];
for (let i = 0; i < intervalCount; i++) {
intervalLog = intervalLog.concat(intervalUnitLog);
}
expect(wtfMock.log[0]).toEqual('# Zone:fork("<root>::ProxyZone::WTF", "TestZone")');
expect(wtfMock.log[1]).toEqual(
'> Zone:invoke:unit-test("<root>::ProxyZone::WTF::TestZone")',
);
expect(wtfMock.log[2]).toContain(
'# Zone:schedule:macroTask:setInterval("<root>::ProxyZone::WTF::TestZone"',
);
expect(wtfMock.log[3]).toEqual('< Zone:invoke:unit-test');
expect(wtfMock.log.splice(4)).toEqual(intervalLog);
clearInterval(cancelId);
done();
});
};
expect(Zone.current.name).toEqual('TestZone');
cancelId = setInterval(intervalFn, 10);
if (isNode) {
expect(typeof cancelId.ref).toEqual('function');
expect(typeof cancelId.unref).toEqual('function');
}
expect(wtfMock.log[0]).toEqual('# Zone:fork("<root>::ProxyZone::WTF", "TestZone")');
expect(wtfMock.log[1]).toEqual(
'> Zone:invoke:unit-test("<root>::ProxyZone::WTF::TestZone")',
);
expect(wtfMock.log[2]).toContain(
'# Zone:schedule:macroTask:setInterval("<root>::ProxyZone::WTF::TestZone"',
);
},
null,
undefined,
'unit-test',
);
});
it('should not cancel the task after invoke the setInterval callback', (done) => {
const logs: HasTaskState[] = [];
const zone = Zone.current.fork({
name: 'interval',
onHasTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
hasTask: HasTaskState,
) => {
logs.push(hasTask);
return delegate.hasTask(targetZone, hasTask);
},
});
zone.run(() => {
const timerId = setInterval(() => {}, 100);
(global as any)[Zone.__symbol__('setTimeout')](() => {
expect(logs.length > 0).toBeTruthy();
expect(logs).toEqual([
{microTask: false, macroTask: true, eventTask: false, change: 'macroTask'},
]);
clearInterval(timerId);
expect(logs).toEqual([
{microTask: false, macroTask: true, eventTask: false, change: 'macroTask'},
{microTask: false, macroTask: false, eventTask: false, change: 'macroTask'},
]);
done();
}, 300);
});
});
});
| {
"end_byte": 3605,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/setInterval.spec.ts"
} |
angular/packages/zone.js/test/common/setTimeout.spec.ts_0_5247 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {patchTimer} from '../../lib/common/timers';
import {isNode, zoneSymbol} from '../../lib/common/utils';
declare const global: any;
const wtfMock = global.wtfMock;
describe('setTimeout', function () {
it('should intercept setTimeout', function (done) {
let cancelId: any;
const testZone = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({name: 'TestZone'});
testZone.run(
() => {
const timeoutFn = function () {
expect(Zone.current.name).toEqual('TestZone');
global[zoneSymbol('setTimeout')](function () {
expect(wtfMock.log[0]).toEqual('# Zone:fork("<root>::ProxyZone::WTF", "TestZone")');
expect(wtfMock.log[1]).toEqual(
'> Zone:invoke:unit-test("<root>::ProxyZone::WTF::TestZone")',
);
expect(wtfMock.log[2]).toContain(
'# Zone:schedule:macroTask:setTimeout("<root>::ProxyZone::WTF::TestZone"',
);
expect(wtfMock.log[3]).toEqual('< Zone:invoke:unit-test');
expect(wtfMock.log[4]).toEqual(
'> Zone:invokeTask:setTimeout("<root>::ProxyZone::WTF::TestZone")',
);
expect(wtfMock.log[5]).toEqual('< Zone:invokeTask:setTimeout');
done();
});
};
expect(Zone.current.name).toEqual('TestZone');
cancelId = setTimeout(timeoutFn, 3);
if (isNode) {
expect(typeof cancelId.ref).toEqual('function');
expect(typeof cancelId.unref).toEqual('function');
}
expect(wtfMock.log[0]).toEqual('# Zone:fork("<root>::ProxyZone::WTF", "TestZone")');
expect(wtfMock.log[1]).toEqual(
'> Zone:invoke:unit-test("<root>::ProxyZone::WTF::TestZone")',
);
expect(wtfMock.log[2]).toContain(
'# Zone:schedule:macroTask:setTimeout("<root>::ProxyZone::WTF::TestZone"',
);
},
null,
undefined,
'unit-test',
);
});
it('should allow canceling of fns registered with setTimeout', function (done) {
const testZone = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({name: 'TestZone'});
testZone.run(() => {
const spy = jasmine.createSpy('spy');
const cancelId = setTimeout(spy, 0);
clearTimeout(cancelId);
setTimeout(function () {
expect(spy).not.toHaveBeenCalled();
done();
}, 1);
});
});
it('should call native clearTimeout with the correct context', function () {
// since clearTimeout has been patched already, we can not test `clearTimeout` directly
// we will fake another API patch to test
let context: any = null;
const fakeGlobal = {
setTimeout: function () {
return 1;
},
clearTimeout: function (id: number) {
context = this;
},
};
patchTimer(fakeGlobal, 'set', 'clear', 'Timeout');
const cancelId = fakeGlobal.setTimeout();
const m = fakeGlobal.clearTimeout;
m.call({}, cancelId);
expect(context).toBe(fakeGlobal);
});
it('should allow cancelation of fns registered with setTimeout after invocation', function (done) {
const testZone = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({name: 'TestZone'});
testZone.run(() => {
const spy = jasmine.createSpy('spy');
const cancelId = setTimeout(spy, 0);
setTimeout(function () {
expect(spy).toHaveBeenCalled();
setTimeout(function () {
clearTimeout(cancelId);
done();
});
}, 1);
});
});
it('should allow cancelation of fns while the task is being executed', function (done) {
const spy = jasmine.createSpy('spy');
const cancelId = setTimeout(() => {
clearTimeout(cancelId);
done();
}, 0);
});
it('should allow cancelation of fns registered with setTimeout during invocation', function (done) {
const testZone = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({name: 'TestZone'});
testZone.run(() => {
const cancelId = setTimeout(function () {
clearTimeout(cancelId);
done();
}, 0);
});
});
it('should return the original timeout Id', function () {
// Node returns complex object from setTimeout, ignore this test.
if (isNode) return;
const cancelId = setTimeout(() => {}, 0);
expect(typeof cancelId).toEqual('number');
});
it('should allow cancelation by numeric timeout Id', function (done) {
// Node returns complex object from setTimeout, ignore this test.
if (isNode) {
done();
return;
}
const testZone = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({name: 'TestZone'});
testZone.run(() => {
const spy = jasmine.createSpy('spy');
const cancelId = setTimeout(spy, 0);
clearTimeout(cancelId);
setTimeout(function () {
expect(spy).not.toHaveBeenCalled();
done();
}, 1);
});
});
it('should pass invalid values through', function () {
clearTimeout(null as any);
clearTimeout(<any>{});
});
});
| {
"end_byte": 5247,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/setTimeout.spec.ts"
} |
angular/packages/zone.js/test/common/promise-disable-wrap-uncaught-promise-rejection.spec.ts_0_3169 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
class TestRejection {
prop1?: string;
prop2?: string;
}
describe('disable wrap uncaught promise rejection', () => {
it('should notify Zone.onHandleError if promise is uncaught', (done) => {
let promiseError: Error | null = null;
let zone: Zone | null = null;
let task: Task | null = null;
let error: Error | null = null;
Zone.current
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
zone = Zone.current;
task = Zone.currentTask;
error = new Error('rejectedErrorShouldBeHandled');
try {
// throw so that the stack trace is captured
throw error;
} catch (e) {}
Promise.reject(error);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError).toBe(error);
expect((promiseError as any)['rejection']).toBe(undefined);
expect((promiseError as any)['zone']).toBe(undefined);
expect((promiseError as any)['task']).toBe(undefined);
done();
});
});
it('should print original information when a non-Error object is used for rejection', (done) => {
let promiseError: Error | null = null;
let rejectObj: TestRejection;
Zone.current
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
rejectObj = new TestRejection();
rejectObj.prop1 = 'value1';
rejectObj.prop2 = 'value2';
(rejectObj as any).message = 'rejectMessage';
Promise.reject(rejectObj);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError).toEqual(rejectObj as any);
done();
});
});
it('should print original information when a primitive value is used for rejection', (done) => {
let promiseError: number | null = null;
Zone.current
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
Promise.reject(42);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError).toBe(42);
done();
});
});
});
| {
"end_byte": 3169,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/promise-disable-wrap-uncaught-promise-rejection.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_0_1231 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const noop = function () {};
let log: {zone: string; taskZone: undefined | string; toState: TaskState; fromState: TaskState}[] =
[];
const detectTask = Zone.current.scheduleMacroTask('detectTask', noop, undefined, noop, noop);
const originalTransitionTo = detectTask.constructor.prototype._transitionTo;
// patch _transitionTo of ZoneTask to add log for test
const logTransitionTo: Function = function (
this: Task & {_state: TaskState},
toState: TaskState,
fromState1: TaskState,
fromState2?: TaskState,
) {
log.push({
zone: Zone.current.name,
taskZone: this.zone && this.zone.name,
toState: toState,
fromState: this._state,
});
originalTransitionTo.apply(this, arguments);
};
function testFnWithLoggedTransitionTo(testFn: Function) {
return function (this: unknown) {
detectTask.constructor.prototype._transitionTo = logTransitionTo;
testFn.apply(this, arguments);
detectTask.constructor.prototype._transitionTo = originalTransitionTo;
};
}
describe('task lifecycle', () => { | {
"end_byte": 1231,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_1234_10309 | describe('event task lifecycle', () => {
beforeEach(() => {
log = [];
});
it(
'task should transit from notScheduled to scheduling then to scheduled state when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduling to unknown when zoneSpec onScheduleTask callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testEventTaskZone',
onScheduleTask: (delegate, currZone, targetZone, task) => {
throw Error('error in onScheduleTask');
},
})
.run(() => {
try {
Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'unknown', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduled to running when task is invoked then from running to scheduled after invoke',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
const task = Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'scheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from scheduled to canceling then from canceling to notScheduled when task is canceled before running',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
const task = Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
Zone.current.cancelTask(task);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from running to canceling then from canceling to notScheduled when task is canceled in running state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
const task = Zone.current.scheduleEventTask(
'testEventTask',
() => {
Zone.current.cancelTask(task);
},
undefined,
noop,
noop,
);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'canceling', fromState: 'running'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from running to scheduled when task.callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
const task = Zone.current.scheduleEventTask(
'testEventTask',
() => {
throw Error('invoke error');
},
undefined,
noop,
noop,
);
try {
task.invoke();
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'scheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from canceling to unknown when zoneSpec.onCancelTask throw error before task running',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
const task = Zone.current.scheduleEventTask(
'testEventTask',
noop,
undefined,
noop,
() => {
throw Error('cancel task');
},
);
try {
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'unknown', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from canceling to unknown when zoneSpec.onCancelTask throw error in running state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testEventTaskZone'}).run(() => {
const task = Zone.current.scheduleEventTask(
'testEventTask',
noop,
undefined,
noop,
() => {
throw Error('cancel task');
},
);
try {
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'unknown', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from notScheduled to scheduled if zoneSpec.onHasTask throw error when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testEventTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
throw Error('hasTask Error');
},
})
.run(() => {
try {
Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit to notScheduled state if zoneSpec.onHasTask throw error when task is canceled',
testFnWithLoggedTransitionTo(() => {
let task: Task;
Zone.current
.fork({
name: 'testEventTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
if (task && task.state === 'canceling') {
throw Error('hasTask Error');
}
},
})
.run(() => {
try {
task = Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
}); | {
"end_byte": 10309,
"start_byte": 1234,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_10313_18295 | describe('non periodical macroTask lifecycle', () => {
beforeEach(() => {
log = [];
});
it(
'task should transit from notScheduled to scheduling then to scheduled state when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
Zone.current.scheduleMacroTask('testMacroTask', noop, undefined, noop, noop);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduling to unknown when zoneSpec onScheduleTask callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testMacroTaskZone',
onScheduleTask: (delegate, currZone, targetZone, task) => {
throw Error('error in onScheduleTask');
},
})
.run(() => {
try {
Zone.current.scheduleMacroTask('testMacroTask', noop, undefined, noop, noop);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'unknown', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduled to running when task is invoked then from running to noScheduled after invoke',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
const task = Zone.current.scheduleMacroTask('testMacroTask', noop, undefined, noop, noop);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from scheduled to canceling then from canceling to notScheduled when task is canceled before running',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
const task = Zone.current.scheduleMacroTask('testMacrotask', noop, undefined, noop, noop);
Zone.current.cancelTask(task);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from running to canceling then from canceling to notScheduled when task is canceled in running state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
const task = Zone.current.scheduleMacroTask(
'testMacroTask',
() => {
Zone.current.cancelTask(task);
},
undefined,
noop,
noop,
);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'canceling', fromState: 'running'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from running to noScheduled when task.callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
const task = Zone.current.scheduleMacroTask(
'testMacroTask',
() => {
throw Error('invoke error');
},
undefined,
noop,
noop,
);
try {
task.invoke();
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from canceling to unknown when zoneSpec.onCancelTask throw error before task running',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
const task = Zone.current.scheduleMacroTask(
'testMacroTask',
noop,
undefined,
noop,
() => {
throw Error('cancel task');
},
);
try {
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'unknown', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from canceling to unknown when zoneSpec.onCancelTask throw error in running state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMacroTaskZone'}).run(() => {
const task = Zone.current.scheduleMacroTask(
'testMacroTask',
noop,
undefined,
noop,
() => {
throw Error('cancel task');
},
);
try {
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'unknown', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from notScheduled to scheduling then to scheduled if zoneSpec.onHasTask throw error when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testMacroTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
throw Error('hasTask Error');
},
})
.run(() => {
try {
Zone.current.scheduleMacroTask('testMacroTask', noop, undefined, noop, noop);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
); | {
"end_byte": 18295,
"start_byte": 10313,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_18301_20566 | it(
'task should transit to notScheduled state if zoneSpec.onHasTask throw error after task.callback being invoked',
testFnWithLoggedTransitionTo(() => {
let task: Task;
Zone.current
.fork({
name: 'testMacroTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
if (task && task.state === 'running') {
throw Error('hasTask Error');
}
},
})
.run(() => {
try {
task = Zone.current.scheduleMacroTask('testMacroTask', noop, undefined, noop, noop);
task.invoke();
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit to notScheduled state if zoneSpec.onHasTask throw error when task is canceled before running',
testFnWithLoggedTransitionTo(() => {
let task: Task;
Zone.current
.fork({
name: 'testMacroTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
if (task && task.state === 'canceling') {
throw Error('hasTask Error');
}
},
})
.run(() => {
try {
task = Zone.current.scheduleMacroTask('testMacroTask', noop, undefined, noop, noop);
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
}); | {
"end_byte": 20566,
"start_byte": 18301,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_20570_29330 | describe('periodical macroTask lifecycle', () => {
let task: Task | null;
beforeEach(() => {
log = [];
task = null;
});
afterEach(() => {
task &&
task.state !== 'notScheduled' &&
task.state !== 'canceling' &&
task.state !== 'unknown' &&
task.zone.cancelTask(task);
});
it(
'task should transit from notScheduled to scheduling then to scheduled state when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
noop,
);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduling to unknown when zoneSpec onScheduleTask callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testPeriodicalTaskZone',
onScheduleTask: (delegate, currZone, targetZone, task) => {
throw Error('error in onScheduleTask');
},
})
.run(() => {
try {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
noop,
);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'unknown', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduled to running when task is invoked then from running to scheduled after invoke',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
noop,
);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'scheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from scheduled to canceling then from canceling to notScheduled when task is canceled before running',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
noop,
);
Zone.current.cancelTask(task);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from running to canceling then from canceling to notScheduled when task is canceled in running state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
() => {
Zone.current.cancelTask(task!);
},
{isPeriodic: true},
noop,
noop,
);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'canceling', fromState: 'running'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from running to scheduled when task.callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
() => {
throw Error('invoke error');
},
{isPeriodic: true},
noop,
noop,
);
try {
task.invoke();
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'scheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from canceling to unknown when zoneSpec.onCancelTask throw error before task running',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
() => {
throw Error('cancel task');
},
);
try {
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'unknown', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from canceling to unknown when zoneSpec.onCancelTask throw error in running state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testPeriodicalTaskZone'}).run(() => {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
() => {
throw Error('cancel task');
},
);
try {
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'unknown', fromState: 'canceling'},
]);
}),
);
it(
'task should transit from notScheduled to scheduled if zoneSpec.onHasTask throw error when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testPeriodicalTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
throw Error('hasTask Error');
},
})
.run(() => {
try {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
noop,
);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
); | {
"end_byte": 29330,
"start_byte": 20570,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_29336_37968 | it(
'task should transit to notScheduled state if zoneSpec.onHasTask throw error when task is canceled',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testPeriodicalTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
if (task && task.state === 'canceling') {
throw Error('hasTask Error');
}
},
})
.run(() => {
try {
task = Zone.current.scheduleMacroTask(
'testPeriodicalTask',
noop,
{isPeriodic: true},
noop,
noop,
);
Zone.current.cancelTask(task);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
});
describe('microTask lifecycle', () => {
beforeEach(() => {
log = [];
});
it(
'task should transit from notScheduled to scheduling then to scheduled state when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMicroTaskZone'}).run(() => {
Zone.current.scheduleMicroTask('testMicroTask', noop, undefined, noop);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduling to unknown when zoneSpec onScheduleTask callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testMicroTaskZone',
onScheduleTask: (delegate, currZone, targetZone, task) => {
throw Error('error in onScheduleTask');
},
})
.run(() => {
try {
Zone.current.scheduleMicroTask('testMicroTask', noop, undefined, noop);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'unknown', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit from scheduled to running when task is invoked then from running to noScheduled after invoke',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMicroTaskZone'}).run(() => {
const task = Zone.current.scheduleMicroTask('testMicroTask', noop, undefined, noop);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'running'},
]);
}),
);
it(
'should throw error when try to cancel a microTask',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMicroTaskZone'}).run(() => {
const task = Zone.current.scheduleMicroTask('testMicroTask', () => {}, undefined, noop);
expect(() => {
Zone.current.cancelTask(task);
}).toThrowError('Task is not cancelable');
});
}),
);
it(
'task should transit from running to notScheduled when task.callback throw error',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testMicroTaskZone'}).run(() => {
const task = Zone.current.scheduleMicroTask(
'testMicroTask',
() => {
throw Error('invoke error');
},
undefined,
noop,
);
try {
task.invoke();
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'running'},
]);
}),
);
it(
'task should transit from notScheduled to scheduling then to scheduled if zoneSpec.onHasTask throw error when scheduleTask',
testFnWithLoggedTransitionTo(() => {
Zone.current
.fork({
name: 'testMicroTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
throw Error('hasTask Error');
},
})
.run(() => {
try {
Zone.current.scheduleMicroTask('testMicroTask', noop, undefined, noop);
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
]);
}),
);
it(
'task should transit to notScheduled state if zoneSpec.onHasTask throw error after task.callback being invoked',
testFnWithLoggedTransitionTo(() => {
let task: Task;
Zone.current
.fork({
name: 'testMicroTaskZone',
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
if (task && task.state === 'running') {
throw Error('hasTask Error');
}
},
})
.run(() => {
try {
task = Zone.current.scheduleMicroTask('testMicroTask', noop, undefined, noop);
task.invoke();
} catch (err) {}
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'running', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'running'},
]);
}),
);
it(
'task should not run if task transite to notScheduled state which was canceled',
testFnWithLoggedTransitionTo(() => {
let task: Task;
Zone.current.fork({name: 'testCancelZone'}).run(() => {
const task = Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
Zone.current.cancelTask(task);
task.invoke();
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
}),
);
});
// Test specific to https://github.com/angular/angular/issues/45711
it('should not throw an error when the task has been canceled previously and is attempted to be canceled again', () => {
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'testCancelZone'}).run(() => {
const task = Zone.current.scheduleEventTask('testEventTask', noop, undefined, noop, noop);
Zone.current.cancelTask(task);
Zone.current.cancelTask(task);
});
expect(
log.map((item) => {
return {toState: item.toState, fromState: item.fromState};
}),
).toEqual([
{toState: 'scheduling', fromState: 'notScheduled'},
{toState: 'scheduled', fromState: 'scheduling'},
{toState: 'canceling', fromState: 'scheduled'},
{toState: 'notScheduled', fromState: 'canceling'},
]);
});
}); | {
"end_byte": 37968,
"start_byte": 29336,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/task.spec.ts_37972_45391 | describe('reschedule zone', () => {
let callbackLogs: ({pos: string; method: string; zone: string; task: string} | HasTaskState)[];
const newZone = Zone.root.fork({
name: 'new',
onScheduleTask: (delegate, currZone, targetZone, task) => {
callbackLogs.push({
pos: 'before',
method: 'onScheduleTask',
zone: currZone.name,
task: task.zone.name,
});
return delegate.scheduleTask(targetZone, task);
},
onInvokeTask: (delegate, currZone, targetZone, task, applyThis, applyArgs) => {
callbackLogs.push({
pos: 'before',
method: 'onInvokeTask',
zone: currZone.name,
task: task.zone.name,
});
return delegate.invokeTask(targetZone, task, applyThis, applyArgs);
},
onCancelTask: (delegate, currZone, targetZone, task) => {
callbackLogs.push({
pos: 'before',
method: 'onCancelTask',
zone: currZone.name,
task: task.zone.name,
});
return delegate.cancelTask(targetZone, task);
},
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
(hasTaskState as any)['zone'] = targetZone.name;
callbackLogs.push(hasTaskState);
return delegate.hasTask(targetZone, hasTaskState);
},
});
const zone = Zone.root.fork({
name: 'original',
onScheduleTask: (delegate, currZone, targetZone, task) => {
callbackLogs.push({
pos: 'before',
method: 'onScheduleTask',
zone: currZone.name,
task: task.zone.name,
});
task.cancelScheduleRequest();
task = newZone.scheduleTask(task);
callbackLogs.push({
pos: 'after',
method: 'onScheduleTask',
zone: currZone.name,
task: task.zone.name,
});
return task;
},
onInvokeTask: (delegate, currZone, targetZone, task, applyThis, applyArgs) => {
callbackLogs.push({
pos: 'before',
method: 'onInvokeTask',
zone: currZone.name,
task: task.zone.name,
});
return delegate.invokeTask(targetZone, task, applyThis, applyArgs);
},
onCancelTask: (delegate, currZone, targetZone, task) => {
callbackLogs.push({
pos: 'before',
method: 'onCancelTask',
zone: currZone.name,
task: task.zone.name,
});
return delegate.cancelTask(targetZone, task);
},
onHasTask: (delegate, currZone, targetZone, hasTaskState) => {
(<any>hasTaskState)['zone'] = targetZone.name;
callbackLogs.push(hasTaskState);
return delegate.hasTask(targetZone, hasTaskState);
},
});
beforeEach(() => {
callbackLogs = [];
});
it(
'should be able to reschedule zone when in scheduling state, after that, task will completely go to new zone, has nothing to do with original one',
testFnWithLoggedTransitionTo(() => {
zone.run(() => {
const t = Zone.current.scheduleMacroTask(
'testRescheduleZoneTask',
noop,
undefined,
noop,
noop,
);
t.invoke();
});
expect(callbackLogs).toEqual([
{pos: 'before', method: 'onScheduleTask', zone: 'original', task: 'original'},
{pos: 'before', method: 'onScheduleTask', zone: 'new', task: 'new'},
{microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'new'},
{pos: 'after', method: 'onScheduleTask', zone: 'original', task: 'new'},
{pos: 'before', method: 'onInvokeTask', zone: 'new', task: 'new'},
{microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'new'},
]);
}),
);
it(
'should not be able to reschedule task in notScheduled / running / canceling state',
testFnWithLoggedTransitionTo(() => {
Zone.current.fork({name: 'rescheduleNotScheduled'}).run(() => {
const t = Zone.current.scheduleMacroTask(
'testRescheduleZoneTask',
noop,
undefined,
noop,
noop,
);
Zone.current.cancelTask(t);
expect(() => {
t.cancelScheduleRequest();
}).toThrow(
Error(
`macroTask 'testRescheduleZoneTask': can not transition to ` +
`'notScheduled', expecting state 'scheduling', was 'notScheduled'.`,
),
);
});
Zone.current
.fork({
name: 'rescheduleRunning',
onInvokeTask: (delegate, currZone, targetZone, task, applyThis, applyArgs) => {
expect(() => {
task.cancelScheduleRequest();
}).toThrow(
Error(
`macroTask 'testRescheduleZoneTask': can not transition to ` +
`'notScheduled', expecting state 'scheduling', was 'running'.`,
),
);
},
})
.run(() => {
const t = Zone.current.scheduleMacroTask(
'testRescheduleZoneTask',
noop,
undefined,
noop,
noop,
);
t.invoke();
});
Zone.current
.fork({
name: 'rescheduleCanceling',
onCancelTask: (delegate, currZone, targetZone, task) => {
expect(() => {
task.cancelScheduleRequest();
}).toThrow(
Error(
`macroTask 'testRescheduleZoneTask': can not transition to ` +
`'notScheduled', expecting state 'scheduling', was 'canceling'.`,
),
);
},
})
.run(() => {
const t = Zone.current.scheduleMacroTask(
'testRescheduleZoneTask',
noop,
undefined,
noop,
noop,
);
Zone.current.cancelTask(t);
});
}),
);
it(
'can not reschedule a task to a zone which is the descendants of the original zone',
testFnWithLoggedTransitionTo(() => {
const originalZone = Zone.root.fork({
name: 'originalZone',
onScheduleTask: (delegate, currZone, targetZone, task) => {
callbackLogs.push({
pos: 'before',
method: 'onScheduleTask',
zone: currZone.name,
task: task.zone.name,
});
task.cancelScheduleRequest();
task = rescheduleZone.scheduleTask(task);
callbackLogs.push({
pos: 'after',
method: 'onScheduleTask',
zone: currZone.name,
task: task.zone.name,
});
return task;
},
});
const rescheduleZone = originalZone.fork({name: 'rescheduleZone'});
expect(() => {
originalZone.run(() => {
Zone.current.scheduleMacroTask('testRescheduleZoneTask', noop, undefined, noop, noop);
});
}).toThrowError(
'can not reschedule task to rescheduleZone which is descendants of the original zone originalZone',
);
}),
);
});
}); | {
"end_byte": 45391,
"start_byte": 37972,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/task.spec.ts"
} |
angular/packages/zone.js/test/common/zone.spec.ts_0_4798 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {zoneSymbol} from '../../lib/common/utils';
describe('Zone', function () {
const rootZone = Zone.current;
it('should have a name', function () {
expect(Zone.current.name).toBeDefined();
});
describe('hooks', function () {
it('should throw if onError is not defined', function () {
expect(function () {
Zone.current.run(throwError);
}).toThrow();
});
it('should fire onError if a function run by a zone throws', function () {
const errorSpy = jasmine.createSpy('error');
const myZone = Zone.current.fork({name: 'spy', onHandleError: errorSpy});
expect(errorSpy).not.toHaveBeenCalled();
expect(function () {
myZone.runGuarded(throwError);
}).not.toThrow();
expect(errorSpy).toHaveBeenCalled();
});
it('should send correct currentZone in hook method when in nested zone', function () {
const zone = Zone.current;
const zoneA = zone.fork({
name: 'A',
onInvoke: function (
parentDelegate,
currentZone,
targetZone,
callback,
applyThis,
applyArgs,
source,
) {
expect(currentZone.name).toEqual('A');
return parentDelegate.invoke(targetZone, callback, applyThis, applyArgs, source);
},
});
const zoneB = zoneA.fork({
name: 'B',
onInvoke: function (
parentDelegate,
currentZone,
targetZone,
callback,
applyThis,
applyArgs,
source,
) {
expect(currentZone.name).toEqual('B');
return parentDelegate.invoke(targetZone, callback, applyThis, applyArgs, source);
},
});
const zoneC = zoneB.fork({name: 'C'});
zoneC.run(function () {});
});
it('should send correct currentZone in hook method when in nested zone with empty implementation', function () {
const zone = Zone.current;
const zoneA = zone.fork({
name: 'A',
onInvoke: function (
parentDelegate,
currentZone,
targetZone,
callback,
applyThis,
applyArgs,
source,
) {
expect(currentZone.name).toEqual('A');
return parentDelegate.invoke(targetZone, callback, applyThis, applyArgs, source);
},
});
const zoneB = zoneA.fork({name: 'B'});
const zoneC = zoneB.fork({name: 'C'});
zoneC.run(function () {});
});
});
it('should allow zones to be run from within another zone', function () {
const zone = Zone.current;
const zoneA = zone.fork({name: 'A'});
const zoneB = zone.fork({name: 'B'});
zoneA.run(function () {
zoneB.run(function () {
expect(Zone.current).toBe(zoneB);
});
expect(Zone.current).toBe(zoneA);
});
expect(Zone.current).toBe(zone);
});
describe('wrap', function () {
it('should throw if argument is not a function', function () {
expect(function () {
(<Function>Zone.current.wrap)(11);
}).toThrowError('Expecting function got: 11');
});
});
describe('run out side of current zone', function () {
it('should be able to get root zone', function () {
Zone.current.fork({name: 'testZone'}).run(function () {
expect(Zone.root.name).toEqual('<root>');
});
});
it('should be able to get run under rootZone', function () {
Zone.current.fork({name: 'testZone'}).run(function () {
Zone.root.run(() => {
expect(Zone.current.name).toEqual('<root>');
});
});
});
it('should be able to get run outside of current zone', function () {
Zone.current.fork({name: 'testZone'}).run(function () {
Zone.root.fork({name: 'newTestZone'}).run(() => {
expect(Zone.current.name).toEqual('newTestZone');
expect(Zone.current.parent!.name).toEqual('<root>');
});
});
});
});
describe('get', function () {
it('should store properties', function () {
const testZone = Zone.current.fork({name: 'A', properties: {key: 'value'}});
expect(testZone.get('key')).toEqual('value');
expect(testZone.getZoneWith('key')).toEqual(testZone);
const childZone = testZone.fork({name: 'B', properties: {key: 'override'}});
expect(testZone.get('key')).toEqual('value');
expect(testZone.getZoneWith('key')).toEqual(testZone);
expect(childZone.get('key')).toEqual('override');
expect(childZone.getZoneWith('key')).toEqual(childZone);
});
}); | {
"end_byte": 4798,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/zone.spec.ts"
} |
angular/packages/zone.js/test/common/zone.spec.ts_4802_12871 | describe('task', () => {
function noop() {}
let log: any[];
const zone: Zone = Zone.current.fork({
name: 'parent',
onHasTask: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
hasTaskState: HasTaskState,
): void => {
(hasTaskState as any)['zone'] = target.name;
log.push(hasTaskState);
},
onScheduleTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task) => {
// Do nothing to prevent tasks from being run on VM turn;
// Tests run task explicitly.
return task;
},
});
beforeEach(() => {
log = [];
});
it('task can only run in the zone of creation', () => {
const task = zone
.fork({name: 'createZone'})
.scheduleMacroTask('test', noop, undefined, noop, noop);
expect(() => {
Zone.current.fork({name: 'anotherZone'}).runTask(task);
}).toThrowError(
'A task can only be run in the zone of creation! (Creation: createZone; Execution: anotherZone)',
);
task.zone.cancelTask(task);
});
it('task can only cancel in the zone of creation', () => {
const task = zone
.fork({name: 'createZone'})
.scheduleMacroTask('test', noop, undefined, noop, noop);
expect(() => {
Zone.current.fork({name: 'anotherZone'}).cancelTask(task);
}).toThrowError(
'A task can only be cancelled in the zone of creation! (Creation: createZone; Execution: anotherZone)',
);
task.zone.cancelTask(task);
});
it('should prevent double cancellation', () => {
const task = zone.scheduleMacroTask(
'test',
() => log.push('macroTask'),
undefined,
noop,
noop,
);
zone.cancelTask(task);
try {
zone.cancelTask(task);
} catch (e) {
expect((e as Error).message).toContain(
"macroTask 'test': can not transition to 'canceling', expecting state 'scheduled' or 'running', was 'notScheduled'.",
);
}
});
it('should not decrement counters on periodic tasks', () => {
zone.run(() => {
const task = zone.scheduleMacroTask(
'test',
() => log.push('macroTask'),
{isPeriodic: true},
noop,
noop,
);
zone.runTask(task);
zone.runTask(task);
zone.cancelTask(task);
});
expect(log).toEqual([
{microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'parent'},
'macroTask',
'macroTask',
{microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'parent'},
]);
});
it('should notify of queue status change', () => {
zone.run(() => {
const z = Zone.current;
z.runTask(z.scheduleMicroTask('test', () => log.push('microTask')));
z.cancelTask(
z.scheduleMacroTask('test', () => log.push('macroTask'), undefined, noop, noop),
);
z.cancelTask(
z.scheduleEventTask('test', () => log.push('eventTask'), undefined, noop, noop),
);
});
expect(log).toEqual([
{microTask: true, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
'microTask',
{microTask: false, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
{microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'parent'},
{microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'parent'},
{microTask: false, macroTask: false, eventTask: true, change: 'eventTask', zone: 'parent'},
{microTask: false, macroTask: false, eventTask: false, change: 'eventTask', zone: 'parent'},
]);
});
it('should notify of queue status change on parent task', () => {
zone.fork({name: 'child'}).run(() => {
const z = Zone.current;
z.runTask(z.scheduleMicroTask('test', () => log.push('microTask')));
});
expect(log).toEqual([
{microTask: true, macroTask: false, eventTask: false, change: 'microTask', zone: 'child'},
{microTask: true, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
'microTask',
{microTask: false, macroTask: false, eventTask: false, change: 'microTask', zone: 'child'},
{microTask: false, macroTask: false, eventTask: false, change: 'microTask', zone: 'parent'},
]);
});
it('should allow rescheduling a task on a separate zone', () => {
const log: any[] = [];
const zone = Zone.current.fork({
name: 'test-root',
onHasTask: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
hasTaskState: HasTaskState,
) => {
(hasTaskState as any)['zone'] = target.name;
log.push(hasTaskState);
},
});
const left = zone.fork({name: 'left'});
const right = zone.fork({
name: 'right',
onScheduleTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task => {
log.push({
pos: 'before',
method: 'onScheduleTask',
zone: current.name,
task: task.zone.name,
});
// Cancel the current scheduling of the task
task.cancelScheduleRequest();
// reschedule on a different zone.
task = left.scheduleTask(task);
log.push({
pos: 'after',
method: 'onScheduleTask',
zone: current.name,
task: task.zone.name,
});
return task;
},
});
const rchild = right.fork({
name: 'rchild',
onScheduleTask: (delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task => {
log.push({
pos: 'before',
method: 'onScheduleTask',
zone: current.name,
task: task.zone.name,
});
task = delegate.scheduleTask(target, task);
log.push({
pos: 'after',
method: 'onScheduleTask',
zone: current.name,
task: task.zone.name,
});
expect((task as any)._zoneDelegates.map((zd: ZoneDelegate) => zd.zone.name)).toEqual([
'left',
'test-root',
'ProxyZone',
]);
return task;
},
});
const task = rchild.scheduleMacroTask('testTask', () => log.push('WORK'), {}, noop, noop);
expect(task.zone).toEqual(left);
log.push(task.zone.name);
task.invoke();
expect(log).toEqual([
{pos: 'before', method: 'onScheduleTask', zone: 'rchild', task: 'rchild'},
{pos: 'before', method: 'onScheduleTask', zone: 'right', task: 'rchild'},
{microTask: false, macroTask: true, eventTask: false, change: 'macroTask', zone: 'left'},
{
microTask: false,
macroTask: true,
eventTask: false,
change: 'macroTask',
zone: 'test-root',
},
{pos: 'after', method: 'onScheduleTask', zone: 'right', task: 'left'},
{pos: 'after', method: 'onScheduleTask', zone: 'rchild', task: 'left'},
'left',
'WORK',
{microTask: false, macroTask: false, eventTask: false, change: 'macroTask', zone: 'left'},
{
microTask: false,
macroTask: false,
eventTask: false,
change: 'macroTask',
zone: 'test-root',
},
]);
});
it('period task should not transit to scheduled state after being cancelled in running state', () => {
const zone = Zone.current.fork({name: 'testZone'});
const task = zone.scheduleMacroTask(
'testPeriodTask',
() => {
zone.cancelTask(task);
},
{isPeriodic: true},
() => {},
() => {},
);
task.invoke();
expect(task.state).toBe('notScheduled');
}); | {
"end_byte": 12871,
"start_byte": 4802,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/zone.spec.ts"
} |
angular/packages/zone.js/test/common/zone.spec.ts_12877_16200 | it('event task should not transit to scheduled state after being cancelled in running state', () => {
const zone = Zone.current.fork({name: 'testZone'});
const task = zone.scheduleEventTask(
'testEventTask',
() => {
zone.cancelTask(task);
},
undefined,
() => {},
() => {},
);
task.invoke();
expect(task.state).toBe('notScheduled');
});
describe('assert ZoneAwarePromise', () => {
it('should not throw when all is OK', () => {
Zone.assertZonePatched();
});
it('should throw error if ZoneAwarePromise has been overwritten', () => {
class WrongPromise {
static resolve(value: any) {}
then() {}
}
const ZoneAwarePromise = global.Promise;
try {
(global as any).Promise = WrongPromise;
expect(() => Zone.assertZonePatched()).toThrow();
} finally {
// restore it.
global.Promise = ZoneAwarePromise;
}
Zone.assertZonePatched();
});
});
});
describe('invoking tasks', () => {
let log: string[];
function noop() {}
beforeEach(() => {
log = [];
});
it('should not drain the microtask queue too early', () => {
const z = Zone.current;
const event = z.scheduleEventTask('test', () => log.push('eventTask'), undefined, noop, noop);
z.scheduleMicroTask('test', () => log.push('microTask'));
const macro = z.scheduleMacroTask(
'test',
() => {
event.invoke();
// At this point, we should not have invoked the microtask.
expect(log).toEqual(['eventTask']);
},
undefined,
noop,
noop,
);
macro.invoke();
});
it('should convert task to json without cyclic error', () => {
const z = Zone.current;
const event = z.scheduleEventTask('test', () => {}, undefined, noop, noop);
const micro = z.scheduleMicroTask('test', () => {});
const macro = z.scheduleMacroTask('test', () => {}, undefined, noop, noop);
expect(function () {
JSON.stringify(event);
}).not.toThrow();
expect(function () {
JSON.stringify(micro);
}).not.toThrow();
expect(function () {
JSON.stringify(macro);
}).not.toThrow();
});
it('should call onHandleError callback when zoneSpec onHasTask throw error', () => {
const spy = jasmine.createSpy('error');
const hasTaskZone = Zone.current.fork({
name: 'hasTask',
onHasTask: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
hasTasState: HasTaskState,
) => {
throw new Error('onHasTask Error');
},
onHandleError: (
delegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: Error,
) => {
spy(error.message);
return delegate.handleError(targetZone, error);
},
});
const microTask = hasTaskZone.scheduleMicroTask(
'test',
() => {},
undefined,
() => {},
);
expect(spy).toHaveBeenCalledWith('onHasTask Error');
});
});
});
function throwError() {
throw new Error();
} | {
"end_byte": 16200,
"start_byte": 12877,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/zone.spec.ts"
} |
angular/packages/zone.js/test/common/toString.spec.ts_0_3688 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {zoneSymbol} from '../../lib/common/utils';
import {ifEnvSupports} from '../test-util';
const g: any =
(typeof window !== 'undefined' && window) || (typeof self !== 'undefined' && self) || global;
describe('global function patch', () => {
describe('isOriginal', () => {
it('setTimeout toString should be the same with non patched setTimeout', () => {
expect(Function.prototype.toString.call(setTimeout)).toEqual(
Function.prototype.toString.call(g[zoneSymbol('setTimeout')]),
);
});
it('should not throw error if Promise is not a function', () => {
const P = g.Promise;
try {
g.Promise = undefined;
expect(() => {
const a = {}.toString();
}).not.toThrow();
} finally {
g.Promise = P;
}
});
it(
'MutationObserver toString should be the same with native version',
ifEnvSupports('MutationObserver', () => {
const nativeMutationObserver = g[zoneSymbol('MutationObserver')];
if (typeof nativeMutationObserver === 'function') {
expect(Function.prototype.toString.call(g['MutationObserver'])).toEqual(
Function.prototype.toString.call(nativeMutationObserver),
);
} else {
expect(Function.prototype.toString.call(g['MutationObserver'])).toEqual(
Object.prototype.toString.call(nativeMutationObserver),
);
}
}),
);
});
describe('isNative', () => {
it('ZoneAwareError toString should look like native', () => {
expect(Function.prototype.toString.call(Error)).toContain('[native code]');
});
it('Function toString should look like native', () => {
expect(Function.prototype.toString.call(Function.prototype.toString)).toContain(
'[native code]',
);
});
it(
'EventTarget addEventListener should look like native',
ifEnvSupports('HTMLElement', () => {
expect(Function.prototype.toString.call(HTMLElement.prototype.addEventListener)).toContain(
'[native code]',
);
}),
);
});
});
describe('ZoneTask', () => {
it('should return handleId.toString if handleId is available', () => {
let macroTask1: any = undefined;
let macroTask2: any = undefined;
let microTask: any = undefined;
const zone = Zone.current.fork({
name: 'timer',
onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type === 'macroTask') {
if (!macroTask1) {
macroTask1 = task;
} else {
macroTask2 = task;
}
} else if (task.type === 'microTask') {
microTask = task;
}
return task;
},
});
zone.run(() => {
const id1 = setTimeout(() => {});
clearTimeout(id1);
const id2 = setTimeout(() => {});
clearTimeout(id2);
Promise.resolve().then(() => {});
const macroTask1Str = macroTask1.toString();
const macroTask2Str = macroTask2.toString();
expect(typeof macroTask1Str).toEqual('string');
expect(macroTask1Str).toEqual(id1.toString());
expect(typeof macroTask2Str).toEqual('string');
expect(macroTask2Str).toEqual(id2.toString());
if (macroTask1.data && typeof macroTask1.data.handleId === 'number') {
expect(macroTask1Str).not.toEqual(macroTask2Str);
}
expect(typeof microTask.toString()).toEqual('string');
});
});
});
| {
"end_byte": 3688,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/toString.spec.ts"
} |
angular/packages/zone.js/test/common/fetch.spec.ts_0_4429 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {isNode} from '../../lib/common/utils';
import {ifEnvSupports, ifEnvSupportsWithDone, isFirefox, isSafari} from '../test-util';
declare const global: any;
describe(
'fetch',
isNode
? () => {
it('is untested for node as the fetch implementation is experimental', () => {});
}
: ifEnvSupports(
'fetch',
function () {
let testZone: Zone;
beforeEach(() => {
testZone = Zone.current.fork({name: 'TestZone'});
});
it('should work for text response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
response.text().then(function (text: string) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(text.trim()).toEqual('{"hello": "world"}');
done();
});
},
);
});
});
it('should work for json response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
response.json().then(function (obj: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(obj.hello).toEqual('world');
done();
});
},
);
});
});
it('should work for blob response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
// Android 4.3- doesn't support response.blob()
if (response.blob) {
response.blob().then(function (blob: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(blob instanceof Blob).toEqual(true);
done();
});
} else {
done();
}
},
);
});
});
it('should work for arrayBuffer response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
// Android 4.3- doesn't support response.arrayBuffer()
if (response.arrayBuffer) {
response.arrayBuffer().then(function (blob: any) {
expect(Zone.current).toBe(fetchZone);
expect(blob instanceof ArrayBuffer).toEqual(true);
done();
});
} else {
done();
}
},
);
});
});
it(
'should throw error when send crendential',
ifEnvSupportsWithDone(isFirefox, function (done: DoneFn) {
testZone.run(function () {
global['fetch']('http://user:password@example.com').then(
function (response: any) {
fail('should not success');
},
(error: any) => {
expect(Zone.current.name).toEqual(testZone.name);
expect(error.constructor.name).toEqual('TypeError');
done();
},
);
});
}),
); | {
"end_byte": 4429,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/fetch.spec.ts"
} |
angular/packages/zone.js/test/common/fetch.spec.ts_4441_12814 | describe('macroTask', () => {
const logs: string[] = [];
let fetchZone: Zone;
let fetchTask: any = null;
beforeEach(() => {
logs.splice(0);
fetchZone = Zone.current.fork({
name: 'fetch',
onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type !== 'eventTask') {
logs.push(`scheduleTask:${task.source}:${task.type}`);
}
if (task.source === 'fetch') {
fetchTask = task;
}
return delegate.scheduleTask(target, task);
},
onInvokeTask: (
delegate: ZoneDelegate,
curr: Zone,
target: Zone,
task: Task,
applyThis: any,
applyArgs: any,
) => {
if (task.type !== 'eventTask') {
logs.push(`invokeTask:${task.source}:${task.type}`);
}
return delegate.invokeTask(target, task, applyThis, applyArgs);
},
onCancelTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type !== 'eventTask') {
logs.push(`cancelTask:${task.source}:${task.type}`);
}
return delegate.cancelTask(target, task);
},
});
});
it('fetch should be considered as macroTask', (done: DoneFn) => {
fetchZone.run(() => {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'invokeTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
// This is the `finally` task, which is used for cleanup.
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
},
);
});
});
// https://github.com/angular/angular/issues/50327
it('Response.json() should be considered as macroTask', (done) => {
fetchZone.run(() => {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then((response: any) => {
const promise = response.json();
// Ensure it's a `ZoneAwarePromise`.
expect(promise).toBeInstanceOf(global.Promise);
return promise;
})
.then(() => {
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'invokeTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
// This is the `finally` task, which is used for cleanup.
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
// Please refer to the issue link above. Previously, `Response` methods were not
// patched by zone.js, and their return values were considered only as
// microtasks (not macrotasks). The Angular zone stabilized prematurely,
// occurring before the resolution of the `response.json()` promise due to the
// falsy value of `zone.hasPendingMacrotasks`. We are now ensuring that
// `Response` methods are treated as macrotasks, similar to the behavior of
// `fetch`.
'scheduleTask:Response.json:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'invokeTask:Response.json:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
});
});
});
it(
'cancel fetch should invoke onCancelTask',
ifEnvSupportsWithDone('AbortController', (done: DoneFn) => {
if (isSafari()) {
// safari not work with AbortController
done();
return;
}
fetchZone.run(() => {
const AbortController = global['AbortController'];
const abort = new AbortController();
const signal = abort.signal;
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json', {
signal,
})
.then(function (response: any) {
fail('should not get response');
})
.catch(function (error: any) {
expect(error.name).toEqual('AbortError');
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'cancelTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
});
abort.abort();
});
}),
);
it(
'cancel fetchTask should trigger abort',
ifEnvSupportsWithDone('AbortController', (done: DoneFn) => {
if (isSafari()) {
// safari not work with AbortController
done();
return;
}
fetchZone.run(() => {
const AbortController = global['AbortController'];
const abort = new AbortController();
const signal = abort.signal;
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json', {
signal,
})
.then(function (response: any) {
fail('should not get response');
})
.catch(function (error: any) {
expect(error.name).toEqual('AbortError');
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'cancelTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
});
fetchTask.zone.cancelTask(fetchTask);
});
}),
);
});
},
emptyRun,
),
);
function emptyRun() {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
} | {
"end_byte": 12814,
"start_byte": 4441,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/fetch.spec.ts"
} |
angular/packages/zone.js/test/common/Error.spec.ts_0_2001 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {isBrowser} from '../../lib/common/utils';
import {isSafari, zoneSymbol} from '../test-util';
// simulate @angular/facade/src/error.ts
class BaseError extends Error {
/** @internal **/
_nativeError: Error;
constructor(message: string) {
super(message);
const nativeError = new Error(message) as any as Error;
this._nativeError = nativeError;
}
override get message() {
return this._nativeError.message;
}
override set message(message) {
this._nativeError.message = message;
}
override get name() {
return this._nativeError.name;
}
override get stack() {
return (this._nativeError as any).stack;
}
override set stack(value) {
(this._nativeError as any).stack = value;
}
override toString() {
return this._nativeError.toString();
}
}
class WrappedError extends BaseError {
originalError: any;
constructor(message: string, error: any) {
super(`${message} caused by: ${error instanceof Error ? error.message : error}`);
this.originalError = error;
}
override get stack() {
return ((this.originalError instanceof Error ? this.originalError : this._nativeError) as any)
.stack;
}
}
class TestError extends WrappedError {
constructor(message: string, error: any) {
super(`${message} caused by: ${error instanceof Error ? error.message : error}`, error);
}
override get message() {
return 'test ' + this.originalError.message;
}
}
class TestMessageError extends WrappedError {
constructor(message: string, error: any) {
super(`${message} caused by: ${error instanceof Error ? error.message : error}`, error);
}
override get message() {
return 'test ' + this.originalError.message;
}
override set message(value) {
this.originalError.message = value;
}
} | {
"end_byte": 2001,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Error.spec.ts"
} |
angular/packages/zone.js/test/common/Error.spec.ts_2003_10210 | describe('ZoneAwareError', () => {
// If the environment does not supports stack rewrites, then these tests will fail
// and there is no point in running them.
const _global: any = typeof window !== 'undefined' ? window : global;
let config: any;
const __karma__ = _global.__karma__;
if (typeof __karma__ !== 'undefined') {
config = __karma__ && (__karma__ as any).config;
} else if (typeof process !== 'undefined') {
config = process.env;
}
const policy = (config && config['errorpolicy']) || 'default';
if (!(Error as any)['stackRewrite'] && policy !== 'disable') return;
it('should keep error prototype chain correctly', () => {
class MyError extends Error {}
const myError = new MyError();
expect(myError instanceof Error).toBe(true);
expect(myError instanceof MyError).toBe(true);
expect(myError.stack).not.toBe(undefined);
});
it('should instanceof error correctly', () => {
let myError = Error('myError');
expect(myError instanceof Error).toBe(true);
let myError1 = Error.call(undefined, 'myError');
expect(myError1 instanceof Error).toBe(true);
let myError2 = Error.call(global, 'myError');
expect(myError2 instanceof Error).toBe(true);
let myError3 = Error.call({}, 'myError');
expect(myError3 instanceof Error).toBe(true);
let myError4 = Error.call({test: 'test'}, 'myError');
expect(myError4 instanceof Error).toBe(true);
});
it('should return error itself from constructor', () => {
class MyError1 extends Error {
constructor() {
const err: any = super('MyError1');
this.message = err.message;
}
}
let myError1 = new MyError1();
expect(myError1.message).toEqual('MyError1');
expect(myError1.name).toEqual('Error');
});
it('should return error by calling error directly', () => {
let myError = Error('myError');
expect(myError.message).toEqual('myError');
let myError1 = Error.call(undefined, 'myError');
expect(myError1.message).toEqual('myError');
let myError2 = Error.call(global, 'myError');
expect(myError2.message).toEqual('myError');
let myError3 = Error.call({}, 'myError');
expect(myError3.message).toEqual('myError');
});
it('should have browser specified property', () => {
let myError = new Error('myError');
if (Object.prototype.hasOwnProperty.call(Error.prototype, 'description')) {
// in IE, error has description property
expect((<any>myError).description).toEqual('myError');
}
if (Object.prototype.hasOwnProperty.call(Error.prototype, 'fileName')) {
// in firefox, error has fileName property
expect((<any>myError).fileName).toBeTruthy();
}
});
it('should not use child Error class get/set in ZoneAwareError constructor', () => {
const func = () => {
const error = new BaseError('test');
expect(error.message).toEqual('test');
};
expect(func).not.toThrow();
});
it('should behave correctly with wrapped error', () => {
const error = new TestError('originalMessage', new Error('error message'));
expect(error.message).toEqual('test error message');
error.originalError.message = 'new error message';
expect(error.message).toEqual('test new error message');
const error1 = new TestMessageError('originalMessage', new Error('error message'));
expect(error1.message).toEqual('test error message');
error1.message = 'new error message';
expect(error1.message).toEqual('test new error message');
});
it('should copy customized NativeError properties to ZoneAwareError', () => {
const spy = jasmine.createSpy('errorCustomFunction');
const NativeError = (global as any)[(Zone as any).__symbol__('Error')];
NativeError.customFunction = function (args: any) {
spy(args);
};
expect((Error as any)['customProperty']).toBe('customProperty');
expect(typeof (Error as any)['customFunction']).toBe('function');
(Error as any)['customFunction']('test');
expect(spy).toHaveBeenCalledWith('test');
});
it('should always have stack property even without throw', () => {
// in IE, the stack will be undefined without throw
// in ZoneAwareError, we will make stack always be
// there event without throw
const error = new Error('test');
const errorWithoutNew = Error('test');
expect(error.stack!.split('\n').length > 0).toBeTruthy();
expect(errorWithoutNew.stack!.split('\n').length > 0).toBeTruthy();
});
it('should show zone names in stack frames and remove extra frames', () => {
if (policy === 'disable' || !(Error as any)['stackRewrite']) {
return;
}
if (isBrowser && isSafari()) {
return;
}
const rootZone = Zone.root;
const innerZone = rootZone.fork({name: 'InnerZone'});
rootZone.run(testFn);
function testFn() {
let outside: any;
let inside: any;
let outsideWithoutNew: any;
let insideWithoutNew: any;
try {
throw new Error('Outside');
} catch (e) {
outside = e;
}
try {
throw Error('Outside');
} catch (e) {
outsideWithoutNew = e;
}
innerZone.run(function insideRun() {
try {
throw new Error('Inside');
} catch (e) {
inside = e;
}
try {
throw Error('Inside');
} catch (e) {
insideWithoutNew = e;
}
});
if (policy === 'lazy') {
outside.stack = outside.zoneAwareStack;
outsideWithoutNew.stack = outsideWithoutNew.zoneAwareStack;
inside.stack = inside.zoneAwareStack;
insideWithoutNew.stack = insideWithoutNew.zoneAwareStack;
}
expect(outside.stack).toEqual(outside.zoneAwareStack);
expect(outsideWithoutNew.stack).toEqual(outsideWithoutNew.zoneAwareStack);
expect(inside!.stack).toEqual(inside!.zoneAwareStack);
expect(insideWithoutNew!.stack).toEqual(insideWithoutNew!.zoneAwareStack);
expect(typeof inside!.originalStack).toEqual('string');
expect(typeof insideWithoutNew!.originalStack).toEqual('string');
const outsideFrames = outside.stack!.split(/\n/);
const insideFrames = inside!.stack!.split(/\n/);
const outsideWithoutNewFrames = outsideWithoutNew!.stack!.split(/\n/);
const insideWithoutNewFrames = insideWithoutNew!.stack!.split(/\n/);
// throw away first line if it contains the error
if (/Outside/.test(outsideFrames[0])) {
outsideFrames.shift();
}
if (/Error /.test(outsideFrames[0])) {
outsideFrames.shift();
}
if (/Outside/.test(outsideWithoutNewFrames[0])) {
outsideWithoutNewFrames.shift();
}
if (/Error /.test(outsideWithoutNewFrames[0])) {
outsideWithoutNewFrames.shift();
}
if (/Inside/.test(insideFrames[0])) {
insideFrames.shift();
}
if (/Error /.test(insideFrames[0])) {
insideFrames.shift();
}
if (/Inside/.test(insideWithoutNewFrames[0])) {
insideWithoutNewFrames.shift();
}
if (/Error /.test(insideWithoutNewFrames[0])) {
insideWithoutNewFrames.shift();
}
expect(outsideFrames[0]).toMatch(/testFn.*[<root>]/);
expect(insideFrames[0]).toMatch(/insideRun.*[InnerZone]]/);
expect(insideFrames[1]).toMatch(/testFn.*[<root>]]/);
expect(outsideWithoutNewFrames[0]).toMatch(/testFn.*[<root>]/);
expect(insideWithoutNewFrames[0]).toMatch(/insideRun.*[InnerZone]]/);
expect(insideWithoutNewFrames[1]).toMatch(/testFn.*[<root>]]/);
}
});
const zoneAwareFrames = [
'Zone.run',
'Zone.runGuarded',
'Zone.scheduleEventTask',
'Zone.scheduleMicroTask',
'Zone.scheduleMacroTask',
'Zone.runTask',
'ZoneDelegate.scheduleTask',
'ZoneDelegate.invokeTask',
'zoneAwareAddListener',
'Zone.prototype.run',
'Zone.prototype.runGuarded',
'Zone.prototype.scheduleEventTask',
'Zone.prototype.scheduleMicroTask',
'Zone.prototype.scheduleMacroTask',
'Zone.prototype.runTask',
'ZoneDelegate.prototype.scheduleTask',
'ZoneDelegate.prototype.invokeTask',
'ZoneTask.invokeTask',
]; | {
"end_byte": 10210,
"start_byte": 2003,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Error.spec.ts"
} |
angular/packages/zone.js/test/common/Error.spec.ts_10214_16563 | function assertStackDoesNotContainZoneFrames(err: any) {
const frames = policy === 'lazy' ? err.zoneAwareStack.split('\n') : err.stack.split('\n');
if (policy === 'disable') {
let hasZoneStack = false;
for (let i = 0; i < frames.length; i++) {
if (hasZoneStack) {
break;
}
hasZoneStack = zoneAwareFrames.filter((f) => frames[i].indexOf(f) !== -1).length > 0;
}
if (!hasZoneStack) {
console.log('stack', hasZoneStack, frames, err.originalStack);
}
expect(hasZoneStack).toBe(true);
} else {
for (let i = 0; i < frames.length; i++) {
expect(zoneAwareFrames.filter((f) => frames[i].indexOf(f) !== -1)).toEqual([]);
}
}
}
const errorZoneSpec = {
name: 'errorZone',
done: <(() => void) | null>null,
onHandleError: (
parentDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: Error,
) => {
assertStackDoesNotContainZoneFrames(error);
setTimeout(() => {
errorZoneSpec.done && errorZoneSpec.done();
}, 0);
return false;
},
};
const errorZone = Zone.root.fork(errorZoneSpec);
const assertStackDoesNotContainZoneFramesTest = function (testFn: Function) {
return function (done: () => void) {
errorZoneSpec.done = done;
errorZone.run(testFn);
};
};
describe('Error stack', () => {
it(
'Error with new which occurs in setTimeout callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
setTimeout(() => {
throw new Error('timeout test error');
}, 10);
}),
);
it(
'Error without new which occurs in setTimeout callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
setTimeout(() => {
throw Error('test error');
}, 10);
}),
);
it('Error with new which cause by promise rejection should not have zone frames visible', (done) => {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('test error'));
});
});
p.catch((err) => {
assertStackDoesNotContainZoneFrames(err);
done();
});
});
it('Error without new which cause by promise rejection should not have zone frames visible', (done) => {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error('test error'));
});
});
p.catch((err) => {
assertStackDoesNotContainZoneFrames(err);
done();
});
});
it(
'Error with new which occurs in eventTask callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.scheduleEventTask(
'errorEvent',
() => {
throw new Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it(
'Error without new which occurs in eventTask callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.scheduleEventTask(
'errorEvent',
() => {
throw Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it(
'Error with new which occurs in longStackTraceZone should not have zone frames and longStackTraceZone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec']).scheduleEventTask(
'errorEvent',
() => {
throw new Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it(
'Error without new which occurs in longStackTraceZone should not have zone frames and longStackTraceZone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec']).scheduleEventTask(
'errorEvent',
() => {
throw Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it(
'stack frames of the callback in user customized zoneSpec should be kept',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current
.fork((Zone as any)['longStackTraceZoneSpec'])
.fork({
name: 'customZone',
onScheduleTask: (parentDelegate, currentZone, targetZone, task) => {
return parentDelegate.scheduleTask(targetZone, task);
},
onHandleError: (parentDelegate, currentZone, targetZone, error) => {
parentDelegate.handleError(targetZone, error);
const containsCustomZoneSpecStackTrace = error.stack.indexOf('onScheduleTask') !== -1;
expect(containsCustomZoneSpecStackTrace).toBeTruthy();
return false;
},
})
.scheduleEventTask(
'errorEvent',
() => {
throw new Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it('should be able to generate zone free stack even NativeError stack is readonly', function () {
const _global: any =
(typeof window === 'object' && window) || (typeof self === 'object' && self) || global;
const NativeError = _global[zoneSymbol('Error')];
const desc = Object.getOwnPropertyDescriptor(NativeError.prototype, 'stack');
if (desc) {
const originalSet: ((value: any) => void) | undefined = desc.set;
// make stack readonly
desc.set = null as any;
try {
const error = new Error('test error');
expect(error.stack).toBeTruthy();
assertStackDoesNotContainZoneFrames(error);
} finally {
desc.set = originalSet;
}
}
});
});
}); | {
"end_byte": 16563,
"start_byte": 10214,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Error.spec.ts"
} |
angular/packages/zone.js/test/common/Promise.spec.ts_0_7528 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {isNode} from '../../lib/common/utils';
import {ifEnvSupports} from '../test-util';
declare const global: any;
class MicroTaskQueueZoneSpec implements ZoneSpec {
name: string = 'MicroTaskQueue';
queue: MicroTask[] = [];
properties = {queue: this.queue, flush: this.flush.bind(this)};
flush() {
while (this.queue.length) {
const task = this.queue.shift();
task!.invoke();
}
}
onScheduleTask(delegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any {
this.queue.push(task as MicroTask);
}
}
function flushMicrotasks() {
Zone.current.get('flush')();
}
class TestRejection {
prop1?: string;
prop2?: string;
}
describe(
'Promise',
ifEnvSupports('Promise', function () {
if (!global.Promise) return;
let log: string[];
let queueZone: Zone;
let testZone: Zone;
let pZone: Zone;
beforeEach(() => {
testZone = Zone.current.fork({name: 'TestZone'});
pZone = Zone.current.fork({
name: 'promise-zone',
onScheduleTask: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): any => {
log.push('scheduleTask');
parentZoneDelegate.scheduleTask(targetZone, task);
},
});
queueZone = Zone.current.fork(new MicroTaskQueueZoneSpec());
log = [];
});
it('should pretend to be a native code', () => {
expect(String(Promise).indexOf('[native code]') >= 0).toBe(true);
});
it('should use native toString for promise instance', () => {
expect(Object.prototype.toString.call(Promise.resolve())).toEqual('[object Promise]');
});
it('should make sure that new Promise is instance of Promise', () => {
expect(Promise.resolve(123) instanceof Promise).toBe(true);
expect(new Promise(() => null) instanceof Promise).toBe(true);
});
it('Promise.resolve(subPromise) should equal to subPromise', () => {
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(p1);
expect(p1).toBe(p2);
});
xit('should ensure that Promise this is instanceof Promise', () => {
expect(() => {
Promise.call({} as any, () => null);
}).toThrowError('Must be an instanceof Promise.');
});
it('should allow subclassing without Symbol.species', () => {
class MyPromise extends Promise<any> {
constructor(fn: any) {
super(fn);
}
}
expect(new MyPromise(() => {}).then(() => null) instanceof MyPromise).toBe(true);
});
it('should allow subclassing without Symbol.species if properties are copied (SystemJS case)', () => {
let value: any = null;
const promise = Promise.resolve();
const systemjsModule = Object.create(null);
// We only copy properties from the `promise` instance onto the `systemjsModule` object.
// This is what SystemJS is doing internally:
// https://github.com/systemjs/systemjs/blob/main/src/system-core.js#L107-L113
for (const property in promise) {
const value: any = promise[property as keyof typeof promise];
if (!(value in systemjsModule) || systemjsModule[property] !== value) {
systemjsModule[property] = value;
}
}
queueZone.run(() => {
Promise.resolve()
.then(() => systemjsModule)
.then((v) => (value = v));
flushMicrotasks();
// Note: we want to ensure that the promise has been resolved. In this specific case
// the promise may resolve to different values in the browser and on the Node.js side.
// SystemJS runs only in the browser and it only needs the promise to be resolved.
expect(value).not.toEqual(null);
});
});
it('should allow subclassing with Symbol.species', () => {
class MyPromise extends Promise<any> {
constructor(fn: any) {
super(fn);
}
static override get [Symbol.species]() {
return MyPromise;
}
}
expect(new MyPromise(() => {}).then(() => null) instanceof MyPromise).toBe(true);
});
it('should allow subclassing with own then', (done: DoneFn) => {
class MyPromise extends Promise<any> {
constructor(private sub: Promise<any>) {
super((resolve) => {
resolve(null);
});
}
override then(onFulfilled: any, onRejected: any) {
return this.sub.then(onFulfilled, onRejected);
}
}
const p = Promise.resolve(1);
new MyPromise(p).then(
(v: any) => {
expect(v).toBe(1);
done();
},
() => done(),
);
});
it('Symbol.species should return ZoneAwarePromise', () => {
const empty = function () {};
const promise = Promise.resolve(1);
const FakePromise = (((promise.constructor = {} as any) as any)[Symbol.species] = function (
exec: any,
) {
exec(empty, empty);
});
expect(promise.then(empty) instanceof FakePromise).toBe(true);
});
it('should intercept scheduling of resolution and then', (done) => {
pZone.run(() => {
let p: Promise<any> = new Promise(function (resolve, reject) {
expect(resolve('RValue')).toBe(undefined);
});
expect(log).toEqual([]);
expect(p instanceof Promise).toBe(true);
p = p.then((v) => {
log.push(v);
expect(v).toBe('RValue');
expect(log).toEqual(['scheduleTask', 'RValue']);
return 'second value';
});
expect(p instanceof Promise).toBe(true);
expect(log).toEqual(['scheduleTask']);
p = p.then((v) => {
log.push(v);
expect(log).toEqual(['scheduleTask', 'RValue', 'scheduleTask', 'second value']);
done();
});
expect(p instanceof Promise).toBe(true);
expect(log).toEqual(['scheduleTask']);
});
});
it('should allow sync resolution of promises', () => {
queueZone.run(() => {
const flush = Zone.current.get('flush');
const queue = Zone.current.get('queue');
const p = new Promise<string>(function (resolve, reject) {
resolve('RValue');
})
.then((v: string) => {
log.push(v);
return 'second value';
})
.then((v: string) => {
log.push(v);
});
expect(queue.length).toEqual(1);
expect(log).toEqual([]);
flush();
expect(log).toEqual(['RValue', 'second value']);
});
});
it('should allow sync resolution of promises returning promises', () => {
queueZone.run(() => {
const flush = Zone.current.get('flush');
const queue = Zone.current.get('queue');
const p = new Promise<string>(function (resolve, reject) {
resolve(Promise.resolve('RValue'));
})
.then((v: string) => {
log.push(v);
return Promise.resolve('second value');
})
.then((v: string) => {
log.push(v);
});
expect(queue.length).toEqual(1);
expect(log).toEqual([]);
flush();
expect(log).toEqual(['RValue', 'second value']);
});
}); | {
"end_byte": 7528,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Promise.spec.ts"
} |
angular/packages/zone.js/test/common/Promise.spec.ts_7534_16866 | describe('Promise API', function () {
it('should work with .then', function (done) {
let resolve: Function | null = null;
testZone.run(function () {
new Promise(function (resolveFn) {
resolve = resolveFn;
}).then(function () {
expect(Zone.current).toBe(testZone);
done();
});
});
resolve!();
});
it('should work with .catch', function (done) {
let reject: (() => void) | null = null;
testZone.run(function () {
new Promise(function (resolveFn, rejectFn) {
reject = rejectFn;
})['catch'](function () {
expect(Zone.current).toBe(testZone);
done();
});
});
expect(reject!()).toBe(undefined);
});
it('should work with .finally with resolved promise', function (done) {
let resolve: Function | null = null;
testZone.run(function () {
(
new Promise(function (resolveFn) {
resolve = resolveFn;
}) as any
).finally(function () {
expect(arguments.length).toBe(0);
expect(Zone.current).toBe(testZone);
done();
});
});
resolve!('value');
});
it('should work with .finally with rejected promise', function (done) {
let reject: Function | null = null;
testZone.run(function () {
(
new Promise(function (_, rejectFn) {
reject = rejectFn;
}) as any
).finally(function () {
expect(arguments.length).toBe(0);
expect(Zone.current).toBe(testZone);
done();
});
});
reject!('error');
});
it('should work with Promise.resolve', () => {
queueZone.run(() => {
let value: any = null;
Promise.resolve('resolveValue').then((v) => (value = v));
expect(Zone.current.get('queue').length).toEqual(1);
flushMicrotasks();
expect(value).toEqual('resolveValue');
});
});
it('should work with Promise.reject', () => {
queueZone.run(() => {
let value: any = null;
Promise.reject('rejectReason')['catch']((v) => (value = v));
expect(Zone.current.get('queue').length).toEqual(1);
flushMicrotasks();
expect(value).toEqual('rejectReason');
});
});
describe('reject', () => {
it('should reject promise', () => {
queueZone.run(() => {
let value: any = null;
Promise.reject('rejectReason')['catch']((v) => (value = v));
flushMicrotasks();
expect(value).toEqual('rejectReason');
});
});
it('should re-reject promise', () => {
queueZone.run(() => {
let value: any = null;
Promise.reject('rejectReason')
['catch']((v) => {
throw v;
})
['catch']((v) => (value = v));
flushMicrotasks();
expect(value).toEqual('rejectReason');
});
});
it('should reject and recover promise', () => {
queueZone.run(() => {
let value: any = null;
Promise.reject('rejectReason')
['catch']((v) => v)
.then((v) => (value = v));
flushMicrotasks();
expect(value).toEqual('rejectReason');
});
});
it('should reject if chained promise does not catch promise', () => {
queueZone.run(() => {
let value: any = null;
Promise.reject('rejectReason')
.then((v) => fail('should not get here'))
.then(null, (v) => (value = v));
flushMicrotasks();
expect(value).toEqual('rejectReason');
});
});
it('should output error to console if ignoreConsoleErrorUncaughtError is false', async () => {
await jasmine.spyOnGlobalErrorsAsync(() => {
const originalConsoleError = console.error;
Zone.current.fork({name: 'promise-error'}).run(() => {
(Zone as any)[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = false;
console.error = jasmine.createSpy('consoleErr');
const p = new Promise((resolve, reject) => {
throw new Error('promise error');
});
});
return new Promise((res) => {
setTimeout(() => {
expect(console.error).toHaveBeenCalled();
console.error = originalConsoleError;
res();
});
});
});
});
it('should not output error to console if ignoreConsoleErrorUncaughtError is true', async () => {
await jasmine.spyOnGlobalErrorsAsync(() => {
const originalConsoleError = console.error;
Zone.current.fork({name: 'promise-error'}).run(() => {
(Zone as any)[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = true;
console.error = jasmine.createSpy('consoleErr');
const p = new Promise((resolve, reject) => {
throw new Error('promise error');
});
});
return new Promise((res) => {
setTimeout(() => {
expect(console.error).not.toHaveBeenCalled();
console.error = originalConsoleError;
(Zone as any)[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = false;
res();
});
});
});
});
it('should notify Zone.onHandleError if no one catches promise', (done) => {
let promiseError: Error | null = null;
let zone: Zone | null = null;
let task: Task | null = null;
let error: Error | null = null;
queueZone
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
zone = Zone.current;
task = Zone.currentTask;
error = new Error('rejectedErrorShouldBeHandled');
try {
// throw so that the stack trace is captured
throw error;
} catch (e) {}
Promise.reject(error);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError!.message).toBe(
'Uncaught (in promise): ' + error + (error!.stack ? '\n' + error!.stack : ''),
);
expect((promiseError as any)['rejection']).toBe(error);
expect((promiseError as any)['zone']).toBe(zone);
expect((promiseError as any)['task']).toBe(task);
done();
});
});
it('should print readable information when throw a not error object', (done) => {
let promiseError: Error | null = null;
let zone: Zone | null = null;
let task: Task | null = null;
let rejectObj: TestRejection;
queueZone
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
zone = Zone.current;
task = Zone.currentTask;
rejectObj = new TestRejection();
rejectObj.prop1 = 'value1';
rejectObj.prop2 = 'value2';
Promise.reject(rejectObj);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError!.message).toMatch(
/Uncaught \(in promise\):.*: {"prop1":"value1","prop2":"value2"}/,
);
done();
});
});
});
describe('Promise.race', () => {
it('should reject the value', () => {
queueZone.run(() => {
let value: any = null;
(Promise as any)
.race([Promise.reject('rejection1'), 'v1'])
['catch']((v: any) => (value = v));
flushMicrotasks();
expect(value).toEqual('rejection1');
});
});
it('should resolve the value', () => {
queueZone.run(() => {
let value: any = null;
(Promise as any)
.race([Promise.resolve('resolution'), 'v1'])
.then((v: any) => (value = v));
flushMicrotasks();
expect(value).toEqual('resolution');
});
});
}); | {
"end_byte": 16866,
"start_byte": 7534,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Promise.spec.ts"
} |
angular/packages/zone.js/test/common/Promise.spec.ts_16874_24699 | describe('Promise.all', () => {
it('should reject the value', () => {
queueZone.run(() => {
let value: any = null;
Promise.all([Promise.reject('rejection'), 'v1'])['catch']((v: any) => (value = v));
flushMicrotasks();
expect(value).toEqual('rejection');
});
});
it('should resolve with the sync then operation', () => {
queueZone.run(() => {
let value: any = null;
const p1 = {
then: function (thenCallback: Function) {
return thenCallback('p1');
},
};
const p2 = {
then: function (thenCallback: Function) {
return thenCallback('p2');
},
};
Promise.all([p1, 'v1', p2]).then((v: any) => (value = v));
flushMicrotasks();
expect(value).toEqual(['p1', 'v1', 'p2']);
});
});
it(
'should resolve generators',
ifEnvSupports(
() => {
return isNode;
},
() => {
const generators: any = function* () {
yield Promise.resolve(1);
yield Promise.resolve(2);
return;
};
queueZone.run(() => {
let value: any = null;
Promise.all(generators()).then((val) => {
value = val;
});
flushMicrotasks();
expect(value).toEqual([1, 2]);
});
},
),
);
it('should handle object with a truthy `then property`', () => {
queueZone.run(() => {
let value: any = null;
Promise.all([{then: 123}]).then((v: any) => (value = v));
flushMicrotasks();
expect(value).toEqual([jasmine.objectContaining({then: 123})]);
});
});
});
});
describe('Promise subclasses', function () {
class MyPromise<T> {
private _promise: Promise<any>;
constructor(init: any) {
this._promise = new Promise(init);
}
catch<TResult = never>(
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,
): Promise<T | TResult> {
return this._promise.catch.call(this._promise, onrejected);
}
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
): Promise<any> {
return this._promise.then.call(this._promise, onfulfilled, onrejected);
}
}
const setPrototypeOf =
(Object as any).setPrototypeOf ||
function (obj: any, proto: any) {
obj.__proto__ = proto;
return obj;
};
setPrototypeOf(MyPromise.prototype, Promise.prototype);
it('should reject if the Promise subclass rejects', function () {
const myPromise = new MyPromise(function (resolve: any, reject: any): void {
reject('foo');
});
return Promise.resolve()
.then(function () {
return myPromise;
})
.then(
function () {
throw new Error('Unexpected resolution');
},
function (result) {
expect(result).toBe('foo');
},
);
});
function testPromiseSubClass(done?: Function) {
const myPromise = new MyPromise(function (resolve: any, reject: Function) {
resolve('foo');
});
return Promise.resolve()
.then(function () {
return myPromise;
})
.then(function (result) {
expect(result).toBe('foo');
done && done();
});
}
it(
'should resolve if the Promise subclass resolves',
jasmine
? function (done) {
testPromiseSubClass(done);
}
: function () {
testPromiseSubClass();
},
);
});
describe('Promise.any', () => {
const any = (Promise as any).any;
it('undefined parameters', (done: DoneFn) => {
any().then(
() => {
fail('should not get a resolved promise.');
},
(err: any) => {
expect(err.message).toEqual('All promises were rejected');
expect(err.errors).toEqual([]);
done();
},
);
});
it('invalid iterable', (done: DoneFn) => {
const invalidIterable: any = {};
invalidIterable[Symbol.iterator] = () => 2;
any(invalidIterable).then(
() => {
fail('should not get a resolved promise.');
},
(err: any) => {
expect(err.message).toEqual('All promises were rejected');
expect(err.errors).toEqual([]);
done();
},
);
});
it('empty parameters', (done: DoneFn) => {
any([]).then(
() => {
fail('should not get a resolved promise.');
},
(err: any) => {
expect(err.message).toEqual('All promises were rejected');
expect(err.errors).toEqual([]);
done();
},
);
});
it('non promises parameters', (done: DoneFn) => {
any([1, 'test']).then(
(v: any) => {
expect(v).toBe(1);
done();
},
(err: any) => {
fail('should not get a rejected promise.');
},
);
});
it('mixed parameters, non promise first', (done: DoneFn) => {
any([1, Promise.resolve(2)]).then(
(v: any) => {
expect(v).toBe(1);
done();
},
(err: any) => {
fail('should not get a rejected promise.');
},
);
});
it('mixed parameters, promise first', (done: DoneFn) => {
any([Promise.resolve(1), 2]).then(
(v: any) => {
expect(v).toBe(1);
done();
},
(err: any) => {
fail('should not get a rejected promise.');
},
);
});
it('all ok promises', (done: DoneFn) => {
any([Promise.resolve(1), Promise.resolve(2)]).then(
(v: any) => {
expect(v).toBe(1);
done();
},
(err: any) => {
fail('should not get a rejected promise.');
},
);
});
it('all promises, first rejected', (done: DoneFn) => {
any([Promise.reject('error'), Promise.resolve(2)]).then(
(v: any) => {
expect(v).toBe(2);
done();
},
(err: any) => {
fail('should not get a rejected promise.');
},
);
});
it('all promises, second rejected', (done: DoneFn) => {
any([Promise.resolve(1), Promise.reject('error')]).then(
(v: any) => {
expect(v).toBe(1);
done();
},
(err: any) => {
fail('should not get a rejected promise.');
},
);
});
it('all rejected promises', (done: DoneFn) => {
any([Promise.reject('error1'), Promise.reject('error2')]).then(
(v: any) => {
fail('should not get a resolved promise.');
},
(err: any) => {
expect(err.message).toEqual('All promises were rejected');
expect(err.errors).toEqual(['error1', 'error2']);
done();
},
);
});
}); | {
"end_byte": 24699,
"start_byte": 16874,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Promise.spec.ts"
} |
angular/packages/zone.js/test/common/Promise.spec.ts_24705_30760 | describe('Promise.allSettled', () => {
const yes = function makeFulfilledResult(value: any) {
return {status: 'fulfilled', value: value};
};
const no = function makeRejectedResult(reason: any) {
return {status: 'rejected', reason: reason};
};
const a = {};
const b = {};
const c = {};
const allSettled = (Promise as any).allSettled;
it('no promise values', (done: DoneFn) => {
allSettled([a, b, c]).then((results: any[]) => {
expect(results).toEqual([yes(a), yes(b), yes(c)]);
done();
});
});
it('all fulfilled', (done: DoneFn) => {
allSettled([Promise.resolve(a), Promise.resolve(b), Promise.resolve(c)]).then(
(results: any[]) => {
expect(results).toEqual([yes(a), yes(b), yes(c)]);
done();
},
);
});
it('all rejected', (done: DoneFn) => {
allSettled([Promise.reject(a), Promise.reject(b), Promise.reject(c)]).then(
(results: any[]) => {
expect(results).toEqual([no(a), no(b), no(c)]);
done();
},
);
});
it('mixed', (done: DoneFn) => {
allSettled([a, Promise.resolve(b), Promise.reject(c)]).then((results: any[]) => {
expect(results).toEqual([yes(a), yes(b), no(c)]);
done();
});
});
it('mixed should in zone', (done: DoneFn) => {
const zone = Zone.current.fork({name: 'settled'});
const bPromise = Promise.resolve(b);
const cPromise = Promise.reject(c);
zone.run(() => {
allSettled([a, bPromise, cPromise]).then((results: any[]) => {
expect(results).toEqual([yes(a), yes(b), no(c)]);
expect(Zone.current.name).toEqual(zone.name);
done();
});
});
});
it('poisoned .then', (done: DoneFn) => {
const promise = new Promise(function () {});
promise.then = function () {
throw new EvalError();
};
allSettled([promise]).then(
() => {
fail('should not reach here');
},
(reason: any) => {
expect(reason instanceof EvalError).toBe(true);
done();
},
);
});
const Subclass = (function () {
try {
// eslint-disable-next-line no-new-func
return Function(
'class Subclass extends Promise { constructor(...args) { super(...args); this.thenArgs = []; } then(...args) { Subclass.thenArgs.push(args); this.thenArgs.push(args); return super.then(...args); } } Subclass.thenArgs = []; return Subclass;',
)();
} catch (e) {
/**/
}
return false;
})();
describe('inheritance', () => {
it('preserves correct subclass', () => {
const promise = allSettled.call(Subclass, [1]);
expect(promise instanceof Subclass).toBe(true);
expect(promise.constructor).toEqual(Subclass);
});
it('invoke the subclass', () => {
Subclass.thenArgs.length = 0;
const original = Subclass.resolve();
expect(Subclass.thenArgs.length).toBe(0);
expect(original.thenArgs.length).toBe(0);
allSettled.call(Subclass, [original]);
expect(original.thenArgs.length).toBe(1);
expect(Subclass.thenArgs.length).toBe(1);
});
});
describe('resolve/reject multiple times', () => {
it('should ignore second resolve', (done) => {
const nested = new Promise((res) => setTimeout(() => res('nested')));
const p = new Promise((res) => {
res(nested);
res(1);
});
p.then((v) => {
expect(v).toBe('nested');
done();
});
});
it('should ignore second resolve', (done) => {
const nested = new Promise((res) => setTimeout(() => res('nested')));
const p = new Promise((res) => {
res(1);
res(nested);
});
p.then((v) => {
expect(v).toBe(1);
done();
});
});
it('should ignore second reject', (done) => {
const p = new Promise((res, rej) => {
rej(1);
rej(2);
});
p.then(
(v) => {
fail('should not get here');
},
(err) => {
expect(err).toBe(1);
done();
},
);
});
it('should ignore resolve after reject', (done) => {
const p = new Promise((res, rej) => {
rej(1);
res(2);
});
p.then(
(v) => {
fail('should not get here');
},
(err) => {
expect(err).toBe(1);
done();
},
);
});
it('should ignore reject after resolve', (done) => {
const nested = new Promise((res) => setTimeout(() => res('nested')));
const p = new Promise((res, rej) => {
res(nested);
rej(1);
});
p.then(
(v) => {
expect(v).toBe('nested');
done();
},
(err) => {
fail('should not be here');
},
);
});
});
});
describe('Promise.withResolvers', () => {
it('should resolve', (done: DoneFn) => {
const {promise, resolve, reject} = (Promise as any).withResolvers();
promise.then((v: any) => {
expect(v).toBe(1);
done();
});
resolve(1);
});
it('should reject', (done: DoneFn) => {
const {promise, resolve, reject} = (Promise as any).withResolvers();
const error = new Error('test');
promise.catch((e: any) => {
expect(e).toBe(error);
done();
});
reject(error);
});
});
}),
); | {
"end_byte": 30760,
"start_byte": 24705,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/common/Promise.spec.ts"
} |
angular/packages/zone.js/test/patch/IndexedDB.spec.js_0_4489 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
'use strict';
describe(
'IndexedDB',
ifEnvSupports('IDBDatabase', function () {
var testZone = zone.fork();
var db;
beforeEach(function (done) {
var openRequest = indexedDB.open('_zone_testdb');
openRequest.onupgradeneeded = function (event) {
db = event.target.result;
var objectStore = db.createObjectStore('test-object-store', {keyPath: 'key'});
objectStore.createIndex('key', 'key', {unique: true});
objectStore.createIndex('data', 'data', {unique: false});
objectStore.transaction.oncomplete = function () {
var testStore = db
.transaction('test-object-store', 'readwrite')
.objectStore('test-object-store');
testStore.add({key: 1, data: 'Test data'});
testStore.transaction.oncomplete = function () {
done();
};
};
};
});
afterEach(function (done) {
db.close();
var openRequest = indexedDB.deleteDatabase('_zone_testdb');
openRequest.onsuccess = function (event) {
done();
};
});
describe('IDBRequest', function () {
it('should bind EventTarget.addEventListener', function (done) {
testZone.run(function () {
db.transaction('test-object-store')
.objectStore('test-object-store')
.get(1)
.addEventListener('success', function (event) {
expect(zone).toBeDirectChildOf(testZone);
expect(event.target.result.data).toBe('Test data');
done();
});
});
});
it('should bind onEventType listeners', function (done) {
testZone.run(function () {
db.transaction('test-object-store').objectStore('test-object-store').get(1).onsuccess =
function (event) {
expect(zone).toBeDirectChildOf(testZone);
expect(event.target.result.data).toBe('Test data');
done();
};
});
});
});
describe('IDBCursor', function () {
it('should bind EventTarget.addEventListener', function (done) {
testZone.run(function () {
db.transaction('test-object-store')
.objectStore('test-object-store')
.openCursor()
.addEventListener('success', function (event) {
var cursor = event.target.result;
if (cursor) {
expect(zone).toBeDirectChildOf(testZone);
expect(cursor.value.data).toBe('Test data');
done();
} else {
throw 'Error while reading cursor!';
}
});
});
});
it('should bind onEventType listeners', function (done) {
testZone.run(function () {
db
.transaction('test-object-store')
.objectStore('test-object-store')
.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
expect(zone).toBeDirectChildOf(testZone);
expect(cursor.value.data).toBe('Test data');
done();
} else {
throw 'Error while reading cursor!';
}
};
});
});
});
describe('IDBIndex', function () {
it('should bind EventTarget.addEventListener', function (done) {
testZone.run(function () {
db.transaction('test-object-store')
.objectStore('test-object-store')
.index('data')
.get('Test data')
.addEventListener('success', function (event) {
expect(zone).toBeDirectChildOf(testZone);
expect(event.target.result.key).toBe(1);
done();
});
});
});
it('should bind onEventType listeners', function (done) {
testZone.run(function () {
db
.transaction('test-object-store')
.objectStore('test-object-store')
.index('data')
.get('Test data').onsuccess = function (event) {
expect(zone).toBeDirectChildOf(testZone);
expect(event.target.result.key).toBe(1);
done();
};
});
});
});
}),
);
| {
"end_byte": 4489,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/patch/IndexedDB.spec.js"
} |
angular/packages/zone.js/test/extra/bluebird.spec.ts_0_590 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// test bluebird promise patch
// this spec will not be integrated with Travis CI, because I don't
// want to add bluebird into devDependencies, you can run this spec
// on your local environment
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
}); | {
"end_byte": 590,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/bluebird.spec.ts"
} |
angular/packages/zone.js/test/extra/bluebird.spec.ts_592_8366 | describe('bluebird promise', () => {
let BluebirdPromise: any;
beforeAll(() => {
BluebirdPromise = require('bluebird');
// install bluebird patch
const {patchBluebird: installBluebird} = require('../../lib/extra/bluebird');
installBluebird(Zone);
const patchBluebird = (Zone as any)[(Zone as any).__symbol__('bluebird')];
patchBluebird(BluebirdPromise);
});
let log: string[];
const zone = Zone.root.fork({
name: 'bluebird',
onScheduleTask: (delegate, curr, targetZone, task) => {
log.push('schedule bluebird task ' + task.source);
return delegate.scheduleTask(targetZone, task);
},
onInvokeTask: (delegate, curr, target, task, applyThis, applyArgs) => {
log.push('invoke bluebird task ' + task.source);
return delegate.invokeTask(target, task, applyThis, applyArgs);
},
});
beforeEach(() => {
log = [];
});
it('bluebird promise then method should be in zone and treated as microTask', (done) => {
zone.run(() => {
const p = new BluebirdPromise((resolve: any, reject: any) => {
setTimeout(() => {
resolve('test');
}, 0);
});
p.then(() => {
expect(Zone.current.name).toEqual('bluebird');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
});
});
});
it('bluebird promise catch method should be in zone and treated as microTask', (done) => {
zone.run(() => {
const p = new BluebirdPromise((resolve: any, reject: any) => {
setTimeout(() => {
reject('test');
}, 0);
});
p.catch(() => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise spread method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.all([
BluebirdPromise.resolve('test1'),
BluebirdPromise.resolve('test2'),
]).spread((r1: string, r2: string) => {
expect(r1).toEqual('test1');
expect(r2).toEqual('test2');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise finally method should be in zone', (done) => {
zone.run(() => {
const p = new BluebirdPromise((resolve: any, reject: any) => {
setTimeout(() => {
resolve('test');
}, 0);
});
p.finally(() => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise join method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.join(
BluebirdPromise.resolve('test1'),
BluebirdPromise.resolve('test2'),
(r1: string, r2: string) => {
expect(r1).toEqual('test1');
expect(r2).toEqual('test2');
expect(Zone.current.name).toEqual('bluebird');
},
).then(() => {
expect(Zone.current.name).toEqual('bluebird');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
});
});
});
it('bluebird promise try method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.try(() => {
throw new Error('promise error');
}).catch((err: Error) => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
expect(err.message).toEqual('promise error');
done();
});
});
});
it('bluebird promise method method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.method(() => {
return 'test';
})().then((result: string) => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
expect(result).toEqual('test');
done();
});
});
});
it('bluebird promise resolve method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.resolve('test').then((result: string) => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
expect(result).toEqual('test');
done();
});
});
});
it('bluebird promise reject method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.reject('error').catch((error: any) => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
expect(error).toEqual('error');
done();
});
});
});
it('bluebird promise all method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.all([
BluebirdPromise.resolve('test1'),
BluebirdPromise.resolve('test2'),
]).then((r: string[]) => {
expect(r[0]).toEqual('test1');
expect(r[1]).toEqual('test2');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise props method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.props({
test1: BluebirdPromise.resolve('test1'),
test2: BluebirdPromise.resolve('test2'),
}).then((r: any) => {
expect(r.test1).toEqual('test1');
expect(r.test2).toEqual('test2');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise any method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.any([
BluebirdPromise.resolve('test1'),
BluebirdPromise.resolve('test2'),
]).then((r: any) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
}); | {
"end_byte": 8366,
"start_byte": 592,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/bluebird.spec.ts"
} |
angular/packages/zone.js/test/extra/bluebird.spec.ts_8370_16355 | it('bluebird promise some method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.some(
[BluebirdPromise.resolve('test1'), BluebirdPromise.resolve('test2')],
1,
).then((r: any) => {
expect(r.length).toBe(1);
expect(r[0]).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise map method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.map(['test1', 'test2'], (value: any) => {
return BluebirdPromise.resolve(value);
}).then((r: string[]) => {
expect(r.length).toBe(2);
expect(r[0]).toEqual('test1');
expect(r[1]).toEqual('test2');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise reduce method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.reduce([1, 2], (total: string, value: string) => {
return BluebirdPromise.resolve(total + value);
}).then((r: number) => {
expect(r).toBe(3);
expect(
log.filter((item) => item === 'schedule bluebird task Promise.then').length,
).toBeTruthy();
expect(
log.filter((item) => item === 'invoke bluebird task Promise.then').length,
).toBeTruthy();
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise filter method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.filter([1, 2, 3], (value: number) => {
return value % 2 === 0 ? BluebirdPromise.resolve(true) : BluebirdPromise.resolve(false);
}).then((r: number[]) => {
expect(r[0]).toBe(2);
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise each method should be in zone', (done) => {
zone.run(() => {
const arr = [1, 2, 3];
BluebirdPromise.each(
BluebirdPromise.map(arr, (item: number) => BluebirdPromise.resolve(item)),
(r: number, idx: number) => {
expect(r).toBe(arr[idx]);
expect(Zone.current.name).toEqual('bluebird');
},
).then((r: any) => {
expect(
log.filter((item) => item === 'schedule bluebird task Promise.then').length,
).toBeTruthy();
expect(
log.filter((item) => item === 'invoke bluebird task Promise.then').length,
).toBeTruthy();
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise mapSeries method should be in zone', (done) => {
zone.run(() => {
const arr = [1, 2, 3];
BluebirdPromise.mapSeries(
BluebirdPromise.map(arr, (item: number) => BluebirdPromise.resolve(item)),
(r: number, idx: number) => {
expect(r).toBe(arr[idx]);
expect(Zone.current.name).toEqual('bluebird');
},
).then((r: any) => {
expect(
log.filter((item) => item === 'schedule bluebird task Promise.then').length,
).toBeTruthy();
expect(
log.filter((item) => item === 'invoke bluebird task Promise.then').length,
).toBeTruthy();
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise race method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.race([
BluebirdPromise.resolve('test1'),
BluebirdPromise.resolve('test2'),
]).then((r: string) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise using/disposer method should be in zone', (done) => {
zone.run(() => {
const p = new BluebirdPromise((resolve: Function, reject: any) => {
setTimeout(() => {
resolve('test');
}, 0);
});
p.leakObj = [];
const disposer = p.disposer(() => {
p.leakObj = null;
});
BluebirdPromise.using(disposer, (v: string) => {
p.leakObj.push(v);
}).then(() => {
expect(Zone.current.name).toEqual('bluebird');
expect(p.leakObj).toBe(null);
// using will generate several promise inside bluebird
expect(
log.filter((item) => item === 'schedule bluebird task Promise.then').length,
).toBeTruthy();
expect(
log.filter((item) => item === 'invoke bluebird task Promise.then').length,
).toBeTruthy();
done();
});
});
});
it('bluebird promise promisify method should be in zone and treated as microTask', (done) => {
const func = (cb: Function) => {
setTimeout(() => {
cb(null, 'test');
}, 10);
};
const promiseFunc = BluebirdPromise.promisify(func);
zone.run(() => {
promiseFunc().then((r: string) => {
expect(Zone.current.name).toEqual('bluebird');
expect(r).toBe('test');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
});
});
});
it('bluebird promise promisifyAll method should be in zone', (done) => {
const obj = {
func1: (cb: Function) => {
setTimeout(() => {
cb(null, 'test1');
}, 10);
},
func2: (cb: Function) => {
setTimeout(() => {
cb(null, 'test2');
}, 10);
},
};
const promiseObj = BluebirdPromise.promisifyAll(obj);
zone.run(() => {
BluebirdPromise.all([promiseObj.func1Async(), promiseObj.func2Async()]).then(
(r: string[]) => {
expect(Zone.current.name).toEqual('bluebird');
expect(r[0]).toBe('test1');
expect(r[1]).toBe('test2');
// using will generate several promise inside
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
},
);
});
});
it('bluebird promise fromCallback method should be in zone', (done) => {
const resolver = (cb: Function) => {
setTimeout(() => {
cb(null, 'test');
}, 10);
};
zone.run(() => {
BluebirdPromise.fromCallback(resolver).then((r: string) => {
expect(Zone.current.name).toEqual('bluebird');
expect(r).toBe('test');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
});
});
});
it('bluebird promise asCallback method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.resolve('test').asCallback((err: Error, r: string) => {
expect(Zone.current.name).toEqual('bluebird');
expect(r).toBe('test');
done();
});
});
}); | {
"end_byte": 16355,
"start_byte": 8370,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/bluebird.spec.ts"
} |
angular/packages/zone.js/test/extra/bluebird.spec.ts_16359_24010 | it('bluebird promise delay method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.resolve('test')
.delay(10)
.then((r: string) => {
expect(Zone.current.name).toEqual('bluebird');
expect(r).toBe('test');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
});
});
});
it('bluebird promise timeout method should be in zone', (done) => {
zone.run(() => {
new BluebirdPromise((resolve: any, reject: any) => {
setTimeout(() => {
resolve('test');
}, 10);
})
.timeout(100)
.then((r: string) => {
expect(Zone.current.name).toEqual('bluebird');
expect(r).toBe('test');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
done();
});
});
});
it('bluebird promise tap method should be in zone', (done) => {
zone.run(() => {
const p = new BluebirdPromise((resolve: any, reject: any) => {
setTimeout(() => {
resolve('test');
}, 0);
});
p.tap(() => {
expect(Zone.current.name).toEqual('bluebird');
}).then(() => {
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(1);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise call method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.map(['test1', 'test2'], (value: any) => {
return BluebirdPromise.resolve(value);
})
.call('shift', (value: any) => {
return value;
})
.then((r: string) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise get method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.resolve(['test1', 'test2'])
.get(-1)
.then((r: string) => {
expect(r).toEqual('test2');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise return method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.resolve()
.return('test1')
.then((r: string) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise throw method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.resolve()
.throw('test1')
.catch((r: string) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise catchReturn method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.reject()
.catchReturn('test1')
.then((r: string) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise catchThrow method should be in zone', (done) => {
zone.run(() => {
BluebirdPromise.reject()
.catchThrow('test1')
.catch((r: string) => {
expect(r).toEqual('test1');
expect(log.filter((item) => item === 'schedule bluebird task Promise.then').length).toBe(
1,
);
expect(log.filter((item) => item === 'invoke bluebird task Promise.then').length).toBe(1);
expect(Zone.current.name).toEqual('bluebird');
done();
});
});
});
it('bluebird promise reflect method should be in zone', (done) => {
zone.run(() => {
const promises = [BluebirdPromise.resolve('test1'), BluebirdPromise.reject('test2')];
BluebirdPromise.all(
promises.map((promise) => {
return promise.reflect();
}),
).each((r: any) => {
if (r.isFulfilled()) {
expect(r.value()).toEqual('test1');
} else {
expect(r.reason()).toEqual('test2');
done();
}
expect(Zone.current.name).toEqual('bluebird');
});
});
});
it('bluebird should be able to run into different zone', (done: Function) => {
Zone.current.fork({name: 'zone_A'}).run(() => {
new BluebirdPromise((resolve: any, reject: any) => {
expect(Zone.current.name).toEqual('zone_A');
resolve(1);
}).then((r: any) => {
expect(Zone.current.name).toEqual('zone_A');
});
});
Zone.current.fork({name: 'zone_B'}).run(() => {
new BluebirdPromise((resolve: any, reject: any) => {
expect(Zone.current.name).toEqual('zone_B');
resolve(2);
}).then((r: any) => {
expect(Zone.current.name).toEqual('zone_B');
done();
});
});
});
it('should be able to chain promise', (done: DoneFn) => {
Zone.current.fork({name: 'zone_A'}).run(() => {
new BluebirdPromise((resolve: any, reject: any) => {
expect(Zone.current.name).toEqual('zone_A');
resolve(1);
})
.then((r: any) => {
expect(r).toBe(1);
expect(Zone.current.name).toEqual('zone_A');
return Promise.resolve(2);
})
.then((r: any) => {
expect(r).toBe(2);
expect(Zone.current.name).toEqual('zone_A');
});
});
Zone.current.fork({name: 'zone_B'}).run(() => {
new BluebirdPromise((resolve: any, reject: any) => {
expect(Zone.current.name).toEqual('zone_B');
reject(1);
})
.then(
() => {
fail('should not be here.');
},
(r: any) => {
expect(r).toBe(1);
expect(Zone.current.name).toEqual('zone_B');
return Promise.resolve(2);
},
)
.then((r: any) => {
expect(r).toBe(2);
expect(Zone.current.name).toEqual('zone_B');
done();
});
});
}); | {
"end_byte": 24010,
"start_byte": 16359,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/bluebird.spec.ts"
} |
angular/packages/zone.js/test/extra/bluebird.spec.ts_24014_28892 | it('should catch rejected chained bluebird promise', (done: DoneFn) => {
const logs: string[] = [];
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
// should not get here
logs.push('onHandleError');
return true;
},
});
zone.runGuarded(() => {
return BluebirdPromise.resolve()
.then(() => {
throw new Error('test error');
})
.catch(() => {
expect(logs).toEqual([]);
done();
});
});
});
it('should catch rejected chained global promise', (done: DoneFn) => {
const logs: string[] = [];
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
// should not get here
logs.push('onHandleError');
return true;
},
});
zone.runGuarded(() => {
return Promise.resolve()
.then(() => {
throw new Error('test error');
})
.catch(() => {
expect(logs).toEqual([]);
done();
});
});
});
it('should catch rejected bluebird promise', (done: DoneFn) => {
const logs: string[] = [];
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
// should not get here
logs.push('onHandleError');
return true;
},
});
zone.runGuarded(() => {
return BluebirdPromise.reject().catch(() => {
expect(logs).toEqual([]);
done();
});
});
});
it('should catch rejected global promise', (done: DoneFn) => {
const logs: string[] = [];
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
// should not get here
logs.push('onHandleError');
return true;
},
});
zone.runGuarded(() => {
return Promise.reject(new Error('reject')).catch(() => {
expect(logs).toEqual([]);
done();
});
});
});
xit('should trigger onHandleError when unhandledRejection', (done: DoneFn) => {
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
setTimeout(done, 100);
return true;
},
});
zone.runGuarded(() => {
return Promise.reject(new Error('reject'));
});
});
xit('should trigger onHandleError when unhandledRejection in chained Promise', (done: DoneFn) => {
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
setTimeout(done, 100);
return true;
},
});
zone.runGuarded(() => {
return Promise.resolve().then(() => {
throw new Error('test');
});
});
});
xit('should not trigger unhandledrejection if zone.onHandleError return false', (done: DoneFn) => {
const listener = function () {
fail('should not be here');
};
if (typeof window !== 'undefined') {
window.addEventListener('unhandledrejection', listener);
} else if (typeof process !== 'undefined') {
process.on('unhandledRejection', listener);
}
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
setTimeout(() => {
if (typeof window !== 'undefined') {
window.removeEventListener('unhandledrejection', listener);
} else if (typeof process !== 'undefined') {
process.removeListener('unhandledRejection', listener);
}
done();
}, 500);
return false;
},
});
zone.runGuarded(() => {
return Promise.resolve().then(() => {
throw new Error('test');
});
});
});
xit('should trigger unhandledrejection if zone.onHandleError return true', (done: DoneFn) => {
const listener = function (event: any) {
if (typeof window !== 'undefined') {
expect(event.detail.reason.message).toEqual('test');
} else if (typeof process !== 'undefined') {
expect(event.message).toEqual('test');
}
if (typeof window !== 'undefined') {
window.removeEventListener('unhandledrejection', listener);
} else if (typeof process !== 'undefined') {
process.removeListener('unhandledRejection', listener);
}
done();
};
if (typeof window !== 'undefined') {
window.addEventListener('unhandledrejection', listener);
} else if (typeof process !== 'undefined') {
process.on('unhandledRejection', listener);
}
const zone = Zone.current.fork({
name: 'testErrorHandling',
onHandleError: function () {
return true;
},
});
zone.runGuarded(() => {
return Promise.resolve().then(() => {
throw new Error('test');
});
});
});
}); | {
"end_byte": 28892,
"start_byte": 24014,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/bluebird.spec.ts"
} |
angular/packages/zone.js/test/extra/electron.js_0_1206 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var domino = require('domino');
var mockRequire = require('mock-require');
var nativeTimeout = setTimeout;
require('./zone-mix.umd');
mockRequire('electron', {
desktopCapturer: {
getSources: function (callback) {
nativeTimeout(callback);
},
},
shell: {
openExternal: function (callback) {
nativeTimeout(callback);
},
},
ipcRenderer: {
on: function (callback) {
nativeTimeout(callback);
},
},
});
require('./zone-patch-electron.umd');
var electron = require('electron');
var zone = Zone.current.fork({name: 'zone'});
zone.run(function () {
electron.desktopCapturer.getSources(function () {
if (Zone.current.name !== 'zone') {
process.exit(1);
}
});
electron.shell.openExternal(function () {
console.log('shell', Zone.current.name);
if (Zone.current.name !== 'zone') {
process.exit(1);
}
});
electron.ipcRenderer.on(function () {
if (Zone.current.name !== 'zone') {
process.exit(1);
}
});
});
| {
"end_byte": 1206,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/electron.js"
} |
angular/packages/zone.js/test/extra/cordova.spec.ts_0_1004 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
describe('cordova test', () => {
it('cordova.exec() should be patched as macroTask', (done) => {
const cordova = (window as any).cordova;
if (!cordova) {
done();
return;
}
const zone = Zone.current.fork({name: 'cordova'});
zone.run(() => {
cordova.exec(
() => {
expect(Zone.current.name).toEqual('cordova');
},
() => {
fail('should not fail');
},
'service',
'successAction',
['arg0', 'arg1'],
);
cordova.exec(
() => {
fail('should not success');
},
() => {
expect(Zone.current.name).toEqual('cordova');
done();
},
'service',
'failAction',
['arg0', 'arg1'],
);
});
});
});
| {
"end_byte": 1004,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/extra/cordova.spec.ts"
} |
angular/packages/zone.js/test/webdriver/test.js_0_1124 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// TODO: @JiaLiPassion, try to add it into travis/saucelabs test after saucelabs support Firefox 52+
// requirement, Firefox 52+, webdriver-manager 12.0.4+, selenium-webdriver 3.3.0+
// test step,
// npx webdriver-manager update
// npx webdriver-manager start
// http-server test/webdriver
// node test/webdriver/test.js
// testcase1: removeEventHandler in firefox cross site context
const webdriver = require('selenium-webdriver');
const capabilities = webdriver.Capabilities.firefox();
const driver = new webdriver.Builder()
.usingServer('http://localhost:4444/wd/hub')
.withCapabilities(capabilities)
.build();
driver.get('http://localhost:8080/test.html');
driver.executeAsyncScript((cb) => {
window.setTimeout(cb, 1000);
});
// test case2 addEventHandler in firefox cross site context
driver
.findElement(webdriver.By.css('#thetext'))
.getText()
.then(function (text) {
console.log(text);
});
| {
"end_byte": 1124,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/webdriver/test.js"
} |
angular/packages/zone.js/test/webdriver/test.sauce.es2015.js_0_2865 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const webdriverio = require('webdriverio');
const desiredCapabilities = {
android60: {
deviceName: 'Android GoogleAPI Emulator',
browserName: 'Chrome',
platformName: 'Android',
platformVersion: '6.0',
deviceOrientation: 'portrait',
appiumVersion: '1.12.1',
},
android71: {
deviceName: 'Android GoogleAPI Emulator',
browserName: 'Chrome',
platformName: 'Android',
platformVersion: '7.1',
deviceOrientation: 'portrait',
appiumVersion: '1.12.1',
},
};
const errors = [];
const tasks = [];
if (process.env.TRAVIS) {
process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join('');
}
Object.keys(desiredCapabilities).forEach((key) => {
console.log('begin webdriver test', key);
if (process.env.TRAVIS) {
desiredCapabilities[key]['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
}
const client = require('webdriverio').remote({
user: process.env.SAUCE_USERNAME,
key: process.env.SAUCE_ACCESS_KEY,
host: 'localhost',
port: 4445,
desiredCapabilities: desiredCapabilities[key],
});
const p = client
.init()
.timeouts('script', 60000)
.url('http://localhost:8080/test/webdriver/test-es2015.html')
.executeAsync(function (done) {
window.setTimeout(done, 1000);
})
.execute(function () {
const elem = document.getElementById('thetext');
const zone = window['Zone'] ? Zone.current.fork({name: 'webdriver'}) : null;
if (zone) {
zone.run(function () {
elem.addEventListener('click', function (e) {
e.target.innerText = 'clicked' + Zone.current.name;
});
});
} else {
elem.addEventListener('click', function (e) {
e.target.innerText = 'clicked';
});
}
})
.click('#thetext')
.getText('#thetext')
.then(
(text) => {
if (text !== 'clickedwebdriver') {
errors.push(`Env: ${key}, expected clickedwebdriver, get ${text}`);
}
},
(error) => {
errors.push(`Env: ${key}, error occurs: ${error}`);
},
)
.end();
tasks.push(p);
});
function exit(exitCode) {
const http = require('http');
http.get('http://localhost:8080/close', () => {
process.exit(exitCode);
});
}
Promise.all(tasks).then(() => {
if (errors.length > 0) {
let nonTimeoutError = false;
errors.forEach((error) => {
console.log(error);
if (error.toString().lastIndexOf('timeout') === -1) {
nonTimeoutError = true;
}
});
if (nonTimeoutError) {
exit(1);
} else {
exit(0);
}
} else {
exit(0);
}
});
| {
"end_byte": 2865,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/webdriver/test.sauce.es2015.js"
} |
angular/packages/zone.js/test/webdriver/test.sauce.js_0_3462 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
const desiredCapabilities = {
firefox52Win7: {browserName: 'firefox', platform: 'Windows 7', version: '52'},
firefox53Win7: {browserName: 'firefox', platform: 'Windows 7', version: '53'},
edge14: {browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '14.14393'},
edge15: {browserName: 'MicrosoftEdge', platform: 'Windows 10', version: '15.15063'},
chrome48: {browserName: 'chrome', version: '48'},
safari8: {browserName: 'safari', platform: 'OS X 10.10', version: '8.0'},
safari9: {browserName: 'safari', platform: 'OS X 10.11', version: '9.0'},
safari10: {browserName: 'safari', platform: 'OS X 10.11', version: '10.0'},
safari11: {browserName: 'safari', platform: 'macOS 10.13', version: '11.1'},
/*ios84: {browserName: 'iphone', platform: 'OS X 10.10', version: '8.4'},*/
ios10: {browserName: 'iphone', platform: 'OS X 10.10', version: '10.3'},
ios11: {browserName: 'iphone', platform: 'OS X 10.12', version: '11.2'},
// andriod44: {browserName: 'android', platform: 'Linux', version: '4.4'},
android51: {browserName: 'android', platform: 'Linux', version: '5.1'},
};
const errors = [];
const tasks = [];
if (process.env.TRAVIS) {
process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join('');
}
Object.keys(desiredCapabilities).forEach((key) => {
console.log('begin webdriver test', key);
if (process.env.TRAVIS) {
desiredCapabilities[key]['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
}
const client = require('webdriverio').remote({
user: process.env.SAUCE_USERNAME,
key: process.env.SAUCE_ACCESS_KEY,
host: 'localhost',
port: 4445,
desiredCapabilities: desiredCapabilities[key],
});
const p = client
.init()
.timeouts('script', 60000)
.url('http://localhost:8080/test/webdriver/test.html')
.executeAsync(function (done) {
window.setTimeout(done, 1000);
})
.execute(function () {
const elem = document.getElementById('thetext');
const zone = window['Zone'] ? Zone.current.fork({name: 'webdriver'}) : null;
if (zone) {
zone.run(function () {
elem.addEventListener('click', function (e) {
e.target.innerText = 'clicked' + Zone.current.name;
});
});
} else {
elem.addEventListener('click', function (e) {
e.target.innerText = 'clicked';
});
}
})
.click('#thetext')
.getText('#thetext')
.then(
(text) => {
if (text !== 'clickedwebdriver') {
errors.push(`Env: ${key}, expected clickedwebdriver, get ${text}`);
}
},
(error) => {
errors.push(`Env: ${key}, error occurs: ${error}`);
},
)
.end();
tasks.push(p);
});
function exit(exitCode) {
const http = require('http');
http.get('http://localhost:8080/close', () => {
process.exit(exitCode);
});
}
Promise.all(tasks).then(() => {
if (errors.length > 0) {
let nonTimeoutError = false;
errors.forEach((error) => {
console.log(error);
if (error.toString().lastIndexOf('timeout') === -1) {
nonTimeoutError = true;
}
});
if (nonTimeoutError) {
exit(1);
} else {
exit(0);
}
} else {
exit(0);
}
});
| {
"end_byte": 3462,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/webdriver/test.sauce.js"
} |
angular/packages/zone.js/test/webdriver/test.html_0_145 | <!DOCTYPE html>
<html>
<head>
<script src='../../dist/zone.js'></script>
</head>
<body>
<div id="thetext">Hello Zones!</div>
</body>
</html>
| {
"end_byte": 145,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/webdriver/test.html"
} |
angular/packages/zone.js/test/webdriver/test-es2015.html_0_155 | <!DOCTYPE html>
<html>
<head>
<script src='../../dist/zone-evergreen.js'></script>
</head>
<body>
<div id="thetext">Hello Zones!</div>
</body>
</html>
| {
"end_byte": 155,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/webdriver/test-es2015.html"
} |
angular/packages/zone.js/test/promise/promise-adapter.mjs_0_444 | import '../../build/zone.umd.js';
Zone[Zone.__symbol__('ignoreConsoleErrorUncaughtError')] = true;
const deferred = function () {
const p = {};
p.promise = new Promise((resolve, reject) => {
p.resolve = resolve;
p.reject = reject;
});
return p;
};
const resolved = (val) => {
return Promise.resolve(val);
};
const rejected = (reason) => {
return Promise.reject(reason);
};
export default {deferred, resolved, rejected};
| {
"end_byte": 444,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/promise/promise-adapter.mjs"
} |
angular/packages/zone.js/test/promise/promise.finally.spec.mjs_0_780 | 'use strict';
import assert from 'assert';
import adapter from './promise-adapter.mjs';
var P = global[Zone.__symbol__('Promise')];
var someRejectionReason = {message: 'some rejection reason'};
var anotherReason = {message: 'another rejection reason'};
process.on('unhandledRejection', function (reason, promise) {
console.log('unhandledRejection', reason);
});
describe('mocha promise sanity check', () => {
it('passes with a resolved promise', () => {
return P.resolve(3);
});
it('passes with a rejected then resolved promise', () => {
return P.reject(someRejectionReason).catch((x) => 'this should be resolved');
});
var ifPromiseIt = P === Promise ? it : it.skip;
ifPromiseIt('is the native Promise', () => {
assert.equal(P, Promise);
});
}); | {
"end_byte": 780,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/promise/promise.finally.spec.mjs"
} |
angular/packages/zone.js/test/promise/promise.finally.spec.mjs_782_9440 | describe('onFinally', () => {
describe('no callback', () => {
specify('from resolved', (done) => {
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally()
.then(
function onFulfilled(x) {
assert.strictEqual(x, 3);
done();
},
function onRejected() {
done(new Error('should not be called'));
}
);
});
specify('from rejected', (done) => {
adapter
.rejected(someRejectionReason)
.catch((e) => {
assert.strictEqual(e, someRejectionReason);
throw e;
})
.finally()
.then(
function onFulfilled() {
done(new Error('should not be called'));
},
function onRejected(reason) {
assert.strictEqual(reason, someRejectionReason);
done();
}
);
});
});
describe('throws an exception', () => {
specify('from resolved', (done) => {
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
throw someRejectionReason;
})
.then(
function onFulfilled() {
done(new Error('should not be called'));
},
function onRejected(reason) {
assert.strictEqual(reason, someRejectionReason);
done();
}
);
});
specify('from rejected', (done) => {
adapter
.rejected(anotherReason)
.finally(function onFinally() {
assert(arguments.length === 0);
throw someRejectionReason;
})
.then(
function onFulfilled() {
done(new Error('should not be called'));
},
function onRejected(reason) {
assert.strictEqual(reason, someRejectionReason);
done();
}
);
});
});
describe('returns a non-promise', () => {
specify('from resolved', (done) => {
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
return 4;
})
.then(
function onFulfilled(x) {
assert.strictEqual(x, 3);
done();
},
function onRejected() {
done(new Error('should not be called'));
}
);
});
specify('from rejected', (done) => {
adapter
.rejected(anotherReason)
.catch((e) => {
assert.strictEqual(e, anotherReason);
throw e;
})
.finally(function onFinally() {
assert(arguments.length === 0);
throw someRejectionReason;
})
.then(
function onFulfilled() {
done(new Error('should not be called'));
},
function onRejected(e) {
assert.strictEqual(e, someRejectionReason);
done();
}
);
});
});
describe('returns a pending-forever promise', () => {
specify('from resolved', (done) => {
var timeout;
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
timeout = setTimeout(done, 0.1e3);
return new P(() => {}); // forever pending
})
.then(
function onFulfilled(x) {
clearTimeout(timeout);
done(new Error('should not be called'));
},
function onRejected() {
clearTimeout(timeout);
done(new Error('should not be called'));
}
);
});
specify('from rejected', (done) => {
var timeout;
adapter
.rejected(someRejectionReason)
.catch((e) => {
assert.strictEqual(e, someRejectionReason);
throw e;
})
.finally(function onFinally() {
assert(arguments.length === 0);
timeout = setTimeout(done, 0.1e3);
return new P(() => {}); // forever pending
})
.then(
function onFulfilled(x) {
clearTimeout(timeout);
done(new Error('should not be called'));
},
function onRejected() {
clearTimeout(timeout);
done(new Error('should not be called'));
}
);
});
});
describe('returns an immediately-fulfilled promise', () => {
specify('from resolved', (done) => {
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
return adapter.resolved(4);
})
.then(
function onFulfilled(x) {
assert.strictEqual(x, 3);
done();
},
function onRejected() {
done(new Error('should not be called'));
}
);
});
specify('from rejected', (done) => {
adapter
.rejected(someRejectionReason)
.catch((e) => {
assert.strictEqual(e, someRejectionReason);
throw e;
})
.finally(function onFinally() {
assert(arguments.length === 0);
return adapter.resolved(4);
})
.then(
function onFulfilled() {
done(new Error('should not be called'));
},
function onRejected(e) {
assert.strictEqual(e, someRejectionReason);
done();
}
);
});
});
describe('returns an immediately-rejected promise', () => {
specify('from resolved ', (done) => {
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
return adapter.rejected(4);
})
.then(
function onFulfilled(x) {
done(new Error('should not be called'));
},
function onRejected(e) {
assert.strictEqual(e, 4);
done();
}
);
});
specify('from rejected', (done) => {
const newReason = {};
adapter
.rejected(someRejectionReason)
.catch((e) => {
assert.strictEqual(e, someRejectionReason);
throw e;
})
.finally(function onFinally() {
assert(arguments.length === 0);
return adapter.rejected(newReason);
})
.then(
function onFulfilled(x) {
done(new Error('should not be called'));
},
function onRejected(e) {
assert.strictEqual(e, newReason);
done();
}
);
});
});
describe('returns a fulfilled-after-a-second promise', () => {
specify('from resolved', (done) => {
var timeout;
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
timeout = setTimeout(done, 1.5e3);
return new P((resolve) => {
setTimeout(() => resolve(4), 1e3);
});
})
.then(
function onFulfilled(x) {
clearTimeout(timeout);
assert.strictEqual(x, 3);
done();
},
function onRejected() {
clearTimeout(timeout);
done(new Error('should not be called'));
}
);
});
specify('from rejected', (done) => {
var timeout;
adapter
.rejected(3)
.catch((e) => {
assert.strictEqual(e, 3);
throw e;
})
.finally(function onFinally() {
assert(arguments.length === 0);
timeout = setTimeout(done, 1.5e3);
return new P((resolve) => {
setTimeout(() => resolve(4), 1e3);
});
})
.then(
function onFulfilled() {
clearTimeout(timeout);
done(new Error('should not be called'));
},
function onRejected(e) {
clearTimeout(timeout);
assert.strictEqual(e, 3);
done();
}
);
});
}); | {
"end_byte": 9440,
"start_byte": 782,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/promise/promise.finally.spec.mjs"
} |
angular/packages/zone.js/test/promise/promise.finally.spec.mjs_9444_11309 | describe('returns a rejected-after-a-second promise', () => {
specify('from resolved', (done) => {
var timeout;
adapter
.resolved(3)
.then((x) => {
assert.strictEqual(x, 3);
return x;
})
.finally(function onFinally() {
assert(arguments.length === 0);
timeout = setTimeout(done, 1.5e3);
return new P((resolve, reject) => {
setTimeout(() => reject(4), 1e3);
});
})
.then(
function onFulfilled() {
clearTimeout(timeout);
done(new Error('should not be called'));
},
function onRejected(e) {
clearTimeout(timeout);
assert.strictEqual(e, 4);
done();
}
);
});
specify('from rejected', (done) => {
var timeout;
adapter
.rejected(someRejectionReason)
.catch((e) => {
assert.strictEqual(e, someRejectionReason);
throw e;
})
.finally(function onFinally() {
assert(arguments.length === 0);
timeout = setTimeout(done, 1.5e3);
return new P((resolve, reject) => {
setTimeout(() => reject(anotherReason), 1e3);
});
})
.then(
function onFulfilled() {
clearTimeout(timeout);
done(new Error('should not be called'));
},
function onRejected(e) {
clearTimeout(timeout);
assert.strictEqual(e, anotherReason);
done();
}
);
});
});
specify('has the correct property descriptor', () => {
var descriptor = Object.getOwnPropertyDescriptor(Promise.prototype, 'finally');
assert.strictEqual(descriptor.writable, true);
assert.strictEqual(descriptor.configurable, true);
});
}); | {
"end_byte": 11309,
"start_byte": 9444,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/promise/promise.finally.spec.mjs"
} |
angular/packages/zone.js/test/rxjs/rxjs.interval.spec.ts_0_1308 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, Observable} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.interval', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'interval func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
if (result >= 3) {
subscriber.unsubscribe();
expect(log).toEqual([0, 1, 2, 3]);
done();
}
},
() => {
fail('should not call error');
},
() => {},
);
});
}, Zone.root),
);
});
| {
"end_byte": 1308,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.interval.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.from.spec.ts_0_2835 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {from, Observable} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.from', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('from array should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return from([1, 2]);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual([1, 2, 'completed']);
});
it('from array like object should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return from('foo');
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual(['f', 'o', 'o', 'completed']);
});
it(
'from promise object should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return from(
new Promise((resolve, reject) => {
resolve(1);
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
(error: any) => {
fail('should not call error' + error);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
expect(log).toEqual([1, 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 2835,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.from.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.range.spec.ts_0_2170 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {asapScheduler, Observable, range} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.range', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('range func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return range(1, 3);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([1, 2, 3, 'completed']);
});
it(
'range func callback should run in the correct zone with scheduler',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return range(1, 3, asapScheduler);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 3, 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 2170,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.range.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.retry.spec.ts_0_1192 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of, throwError, timer} from 'rxjs';
import {catchError, finalize, mergeMap, retryWhen} from 'rxjs/operators';
describe('retryWhen', () => {
let log: any[];
const genericRetryStrategy = (finalizer: () => void) => (attempts: Observable<any>) =>
attempts.pipe(
mergeMap((error, i) => {
const retryAttempt = i + 1;
if (retryAttempt > 3) {
return throwError(error);
}
log.push(error);
return timer(retryAttempt * 1);
}),
finalize(() => finalizer()),
);
const errorGenerator = () => {
return throwError(new Error('error emit'));
};
beforeEach(() => {
log = [];
});
it('should retry max 3 times', (done: DoneFn) => {
errorGenerator()
.pipe(
retryWhen(
genericRetryStrategy(() => {
expect(log.length).toBe(3);
done();
}),
),
catchError((error) => of(error)),
)
.subscribe();
});
});
| {
"end_byte": 1192,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.retry.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.merge.spec.ts_0_8430 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, merge, Observable, of, range} from 'rxjs';
import {
expand,
map,
mergeAll,
mergeMap,
mergeMapTo,
switchAll,
switchMap,
switchMapTo,
take,
} from 'rxjs/operators';
import {asyncTest, ifEnvSupports} from '../test-util';
import {supportFeature} from './rxjs.util';
describe('Observable.merge', () => {
let log: any[];
let observable1: Observable<any>;
let defaultTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
beforeEach(() => {
log = [];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = defaultTimeout;
});
it('expand func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const expandZone1: Zone = Zone.current.fork({name: 'Expand Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(2);
});
observable1 = expandZone1.run(() => {
return observable1.pipe(
expand((val: any) => {
expect(Zone.current.name).toEqual(expandZone1.name);
return of(1 + val);
}),
take(2),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([2, 3, 'completed']);
});
it(
'merge func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return merge(interval(10).pipe(take(2)), interval(15).pipe(take(1)));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 0, 1, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'mergeAll func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2).pipe(
map((v: any) => {
return of(v + 1);
}),
mergeAll(),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 3, 'completed']);
done();
},
);
});
}, Zone.root),
);
it('mergeMap func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2).pipe(
mergeMap((v: any) => {
return of(v + 1);
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 3, 'completed']);
},
);
});
});
it('mergeMapTo func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2).pipe(mergeMapTo(of(10)));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([10, 10, 'completed']);
},
);
});
});
it('switch func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return range(0, 3).pipe(
map(function (x: any) {
return range(x, 3);
}),
switchAll(),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 1, 2, 3, 2, 3, 4, 'completed']);
},
);
});
});
it('switchMap func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return range(0, 3).pipe(
switchMap(function (x: any) {
return range(x, 3);
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 1, 2, 3, 2, 3, 4, 'completed']);
},
);
});
});
it('switchMapTo func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return range(0, 3).pipe(switchMapTo('a'));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['a', 'a', 'a', 'completed']);
},
);
});
});
});
| {
"end_byte": 8430,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.merge.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.audit.spec.ts_0_2781 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, Observable} from 'rxjs';
import {audit, auditTime} from 'rxjs/operators';
import {asyncTest} from '../test-util';
xdescribe('Observable.audit', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'audit func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = interval(100);
return source.pipe(
audit((ev) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return interval(150);
}),
);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
if (result >= 3) {
subscriber.unsubscribe();
}
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 3, 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
xit(
'auditTime func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const source = interval(100);
return source.pipe(auditTime(360));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
if (result >= 7) {
subscriber.unsubscribe();
}
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([3, 7, 'completed']);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 2781,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.audit.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.never.spec.ts_0_1137 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NEVER, Observable} from 'rxjs';
import {startWith} from 'rxjs/operators';
describe('Observable.never', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('never func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return NEVER.pipe(startWith(7));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
fail('should not call complete');
},
);
});
expect(log).toEqual([7]);
});
});
| {
"end_byte": 1137,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.never.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.retry.spec.ts_0_1740 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of, timer} from 'rxjs';
import {delayWhen, map, retryWhen} from 'rxjs/operators';
describe('Observable.retryWhen', () => {
let log: any[];
let observable1: Observable<any>;
let defaultTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
beforeEach(() => {
log = [];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = defaultTimeout;
});
it('retryWhen func callback should run in the correct zone', (done: DoneFn) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let isErrorHandled = false;
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(
map((v) => {
if (v > 2 && !isErrorHandled) {
isErrorHandled = true;
throw v;
}
return v;
}),
retryWhen((err) => err.pipe(delayWhen((v) => timer(v)))),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 1, 2, 3, 'completed']);
done();
},
);
});
});
});
| {
"end_byte": 1740,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.retry.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.merge.spec.ts_0_1926 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, merge, Observable} from 'rxjs';
import {map, take} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.merge', () => {
let log: any[];
beforeEach(() => {
log = [];
});
it(
'merge func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const constructorZone3: Zone = Zone.current.fork({name: 'Constructor Zone3'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const observable1: any = constructorZone1.run(() => {
return interval(8).pipe(
map((v) => 'observable1' + v),
take(1),
);
});
const observable2: any = constructorZone2.run(() => {
return interval(10).pipe(
map((v) => 'observable2' + v),
take(1),
);
});
const observable3: any = constructorZone3.run(() => {
return merge(observable1, observable2);
});
subscriptionZone.run(() => {
const subscriber = observable3.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['observable10', 'observable20', 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 1926,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.merge.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.debounce.spec.ts_0_2478 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of, timer} from 'rxjs';
import {debounce, debounceTime} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.debounce', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'debounce func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(
debounce(() => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return timer(100);
}),
);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
done();
},
);
});
expect(log).toEqual([3, 'completed']);
}, Zone.root),
);
it(
'debounceTime func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(debounceTime(100));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
done();
},
);
});
expect(log).toEqual([3, 'completed']);
}, Zone.root),
);
});
| {
"end_byte": 2478,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.debounce.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.distinct.spec.ts_0_3343 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of} from 'rxjs';
import {distinct, distinctUntilChanged, distinctUntilKeyChanged} from 'rxjs/operators';
describe('Observable.distinct', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('distinct func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1).pipe(distinct());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([1, 2, 3, 4, 'completed']);
});
it('distinctUntilChanged func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 1, 2, 2, 2, 1, 1, 2, 3, 3, 4).pipe(distinctUntilChanged());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([1, 2, 1, 2, 3, 4, 'completed']);
});
it('distinctUntilKeyChanged func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(
{age: 4, name: 'Foo'},
{age: 7, name: 'Bar'},
{age: 5, name: 'Foo'},
{age: 6, name: 'Foo'},
).pipe(distinctUntilKeyChanged('name'));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([
{age: 4, name: 'Foo'},
{age: 7, name: 'Bar'},
{age: 5, name: 'Foo'},
'completed',
]);
});
});
| {
"end_byte": 3343,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.distinct.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.bindCallback.spec.ts_0_2613 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {asapScheduler, bindCallback} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.bindCallback', () => {
let log: any[];
const constructorZone: Zone = Zone.root.fork({name: 'Constructor Zone'});
const subscriptionZone: Zone = Zone.root.fork({name: 'Subscription Zone'});
let func: any;
let boundFunc: any;
let observable: any;
beforeEach(() => {
log = [];
});
it('bindCallback func callback should run in the correct zone', () => {
constructorZone.run(() => {
func = function (arg0: any, callback: Function) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(arg0);
};
boundFunc = bindCallback(func);
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe((arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
});
});
expect(log).toEqual(['nexttest']);
});
it('bindCallback with selector should run in correct zone', () => {
constructorZone.run(() => {
func = function (arg0: any, callback: Function) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(arg0);
};
boundFunc = bindCallback(func, (arg: any) => {
expect(Zone.current.name).toEqual(constructorZone.name);
return 'selector' + arg;
});
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe((arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
});
});
expect(log).toEqual(['nextselectortest']);
});
it(
'bindCallback with async scheduler should run in correct zone',
asyncTest((done: any) => {
constructorZone.run(() => {
func = function (arg0: any, callback: Function) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(arg0);
};
boundFunc = bindCallback(func, () => true, asapScheduler);
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe((arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
done();
});
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 2613,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.bindCallback.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.timeout.spec.ts_0_2161 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of} from 'rxjs';
import {timeout} from 'rxjs/operators';
import {asyncTest, isPhantomJS} from '../test-util';
describe('Observable.timeout', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'timeout func callback should run in the correct zone',
asyncTest((done: any) => {
if (isPhantomJS()) {
done();
return;
}
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1).pipe(timeout(10));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'promise should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const promise: any = constructorZone1.run(() => {
return of(1).toPromise();
});
subscriptionZone.run(() => {
promise.then(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(result).toEqual(1);
done();
},
(err: any) => {
fail('should not call error');
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 2161,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.timeout.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.sample.spec.ts_0_2559 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, Observable} from 'rxjs';
import {sample, take, throttle} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.sample', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'sample func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10).pipe(sample(interval(15)));
});
subscriptionZone.run(() => {
const subscriber: any = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
subscriber.complete();
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 'completed']);
done();
},
);
});
}, Zone.root),
);
xit(
'throttle func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10).pipe(
take(5),
throttle((val: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return interval(20);
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 2, 4, 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 2559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.sample.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.throw.spec.ts_0_2129 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {asapScheduler, Observable, throwError} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.throw', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('throw func callback should run in the correct zone', () => {
let error = new Error('test');
observable1 = constructorZone1.run(() => {
return throwError(error);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
fail('should not call next');
},
(error: any) => {
log.push(error);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call complete');
},
);
});
expect(log).toEqual([error]);
});
it(
'throw func callback should run in the correct zone with scheduler',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let error = new Error('test');
observable1 = constructorZone1.run(() => {
return throwError(error, asapScheduler);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
fail('should not call next');
},
(error: any) => {
log.push(error);
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([error]);
done();
},
() => {
fail('should not call complete');
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 2129,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.throw.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.concat.spec.ts_0_7038 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {asapScheduler, concat, Observable, of, range} from 'rxjs';
import {concatAll, concatMap, concatMapTo, map} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable instance method concat', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const constructorZone3: Zone = Zone.current.fork({name: 'Constructor Zone3'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
let observable2: any;
let concatObservable: any;
beforeEach(() => {
log = [];
});
it('concat func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return new Observable((subscriber) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
});
observable2 = constructorZone2.run(() => {
return range(3, 4);
});
constructorZone3.run(() => {
concatObservable = concat(observable1, observable2);
});
subscriptionZone.run(() => {
concatObservable.subscribe((concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
});
});
expect(log).toEqual([1, 2, 3, 4, 5, 6]);
});
xit(
'concat func callback should run in the correct zone with scheduler',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const constructorZone3: Zone = Zone.current.fork({name: 'Constructor Zone3'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2);
});
observable2 = constructorZone2.run(() => {
return range(3, 4);
});
constructorZone3.run(() => {
concatObservable = concat(observable1, observable2, asapScheduler);
});
subscriptionZone.run(() => {
concatObservable.subscribe(
(concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
},
(error: any) => {
fail('subscribe failed' + error);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 3, 4, 5, 6]);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
it(
'concatAll func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(0, 1, 2);
});
constructorZone2.run(() => {
const highOrder = observable1.pipe(
map((v: any) => {
expect(Zone.current.name).toEqual(constructorZone2.name);
return of(v + 1);
}),
);
concatObservable = highOrder.pipe(concatAll());
});
subscriptionZone.run(() => {
concatObservable.subscribe(
(concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
},
(error: any) => {
fail('subscribe failed' + error);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 3]);
done();
},
);
});
}, Zone.root),
);
it(
'concatMap func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return new Observable((subscriber) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.next(4);
subscriber.complete();
});
});
constructorZone2.run(() => {
concatObservable = observable1.pipe(
concatMap((v: any) => {
expect(Zone.current.name).toEqual(constructorZone2.name);
return of(0, 1);
}),
);
});
subscriptionZone.run(() => {
concatObservable.subscribe(
(concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
},
(error: any) => {
fail('subscribe failed' + error);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 0, 1, 0, 1, 0, 1]);
done();
},
);
});
}, Zone.root),
);
it(
'concatMapTo func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return new Observable((subscriber) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.next(4);
subscriber.complete();
});
});
constructorZone2.run(() => {
concatObservable = observable1.pipe(concatMapTo(of(0, 1)));
});
subscriptionZone.run(() => {
concatObservable.subscribe(
(concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
},
(error: any) => {
fail('subscribe failed' + error);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 0, 1, 0, 1, 0, 1]);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 7038,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.concat.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.multicast.spec.ts_0_2500 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of, Subject} from 'rxjs';
import {mapTo, multicast, tap} from 'rxjs/operators';
// TODO: @JiaLiPassion, Observable.prototype.multicast return a readonly _subscribe
// should find another way to patch subscribe
describe('Observable.multicast', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const doZone1: Zone = Zone.current.fork({name: 'Do Zone1'});
const mapZone1: Zone = Zone.current.fork({name: 'Map Zone1'});
const multicastZone1: Zone = Zone.current.fork({name: 'Multicast Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('multicast func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = doZone1.run(() => {
return observable1.pipe(
tap((v: any) => {
expect(Zone.current.name).toEqual(doZone1.name);
log.push('do' + v);
}),
);
});
observable1 = mapZone1.run(() => {
return observable1.pipe(mapTo('test'));
});
const multi: any = multicastZone1.run(() => {
return observable1.pipe(
multicast(() => {
expect(Zone.current.name).toEqual(multicastZone1.name);
return new Subject();
}),
);
});
multi.subscribe((val: any) => {
log.push('one' + val);
});
multi.subscribe((val: any) => {
log.push('two' + val);
});
multi.connect();
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([
'do1',
'onetest',
'twotest',
'do2',
'onetest',
'twotest',
'do3',
'onetest',
'twotest',
'do1',
'test',
'do2',
'test',
'do3',
'test',
'completed',
]);
});
});
| {
"end_byte": 2500,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.multicast.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.do.spec.ts_0_1522 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of} from 'rxjs';
import {tap} from 'rxjs/operators';
describe('Observable.tap', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('do func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const doZone1: Zone = Zone.current.fork({name: 'Do Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1);
});
observable1 = doZone1.run(() => {
return observable1.pipe(
tap((v: any) => {
log.push(v);
expect(Zone.current.name).toEqual(doZone1.name);
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push('result' + result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 'result1', 'completed']);
},
);
});
});
});
| {
"end_byte": 1522,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.do.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.default.spec.ts_0_1408 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of} from 'rxjs';
import {defaultIfEmpty} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.defaultIfEmpty', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'defaultIfEmpty func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of().pipe(defaultIfEmpty('empty' as any));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['empty', 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 1408,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.default.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.empty.spec.ts_0_1015 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {empty, Observable} from 'rxjs';
describe('Observable.empty', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('empty func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return empty();
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
fail('should not call next');
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
});
});
| {
"end_byte": 1015,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.empty.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.timer.spec.ts_0_1474 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, timer} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.timer', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'timer func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return timer(10, 20);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
if (result >= 3) {
// subscriber.complete();
subscriber.unsubscribe();
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 3, 'completed']);
done();
}
},
() => {
fail('should not call error');
},
);
expect(log).toEqual([]);
});
}, Zone.root),
);
});
| {
"end_byte": 1474,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.timer.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.fromEvent.spec.ts_0_3335 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {fromEvent, fromEventPattern, Observable} from 'rxjs';
import {isBrowser} from '../../lib/common/utils';
import {ifEnvSupports} from '../test-util';
function isEventTarget() {
return isBrowser;
}
(isEventTarget as any).message = 'EventTargetTest';
describe('Observable.fromEvent', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const triggerZone: Zone = Zone.current.fork({name: 'Trigger Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'fromEvent EventTarget func callback should run in the correct zone',
ifEnvSupports(isEventTarget, () => {
observable1 = constructorZone1.run(() => {
return fromEvent(document, 'click');
});
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
triggerZone.run(() => {
document.dispatchEvent(clickEvent);
});
expect(log).toEqual([clickEvent]);
}),
);
it(
'fromEventPattern EventTarget func callback should run in the correct zone',
ifEnvSupports(isEventTarget, () => {
const button = document.createElement('button');
document.body.appendChild(button);
observable1 = constructorZone1.run(() => {
return fromEventPattern(
(handler: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
button.addEventListener('click', handler);
log.push('addListener');
},
(handler: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
button.removeEventListener('click', handler);
document.body.removeChild(button);
log.push('removeListener');
},
);
});
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', false, false);
const subscriper: any = subscriptionZone.run(() => {
return observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
triggerZone.run(() => {
button.dispatchEvent(clickEvent);
subscriper.complete();
});
expect(log).toEqual(['addListener', clickEvent, 'completed', 'removeListener']);
}),
);
});
| {
"end_byte": 3335,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.fromEvent.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.of.spec.ts_0_1149 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of} from 'rxjs';
describe('Observable.of', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('of func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual([1, 2, 3, 'completed']);
});
});
| {
"end_byte": 1149,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.of.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.forkjoin.spec.ts_0_1979 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {forkJoin, from, Observable, range} from 'rxjs';
describe('Observable.forkjoin', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('forkjoin func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return forkJoin(range(1, 2), from([4, 5]));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual([[2, 5], 'completed']);
});
it('forkjoin func callback with selector should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return forkJoin(range(1, 2), from([4, 5]), (x: number, y: number) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return x + y;
});
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual([7, 'completed']);
});
});
| {
"end_byte": 1979,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.forkjoin.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.delay.spec.ts_0_2383 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of, timer} from 'rxjs';
import {delay, delayWhen} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.delay', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'delay func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(delay(100));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 3, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'delayWhen func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(
delayWhen((v: any) => {
return timer(v * 10);
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 3, 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 2383,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.delay.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.catch.spec.ts_0_2803 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, of} from 'rxjs';
import {catchError, map, retry} from 'rxjs/operators';
describe('Observable.catch', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('catch func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const error = new Error('test');
const source = of(1, 2, 3).pipe(
map((n: number) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
if (n === 2) {
throw error;
}
return n;
}),
);
return source.pipe(
catchError((err: any) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return of('error1', 'error2');
}),
);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([1, 'error1', 'error2', 'completed']);
});
it('retry func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(
map((n: number) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
if (n === 2) {
throw error;
}
return n;
}),
retry(1),
);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
(error: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(error);
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([1, 1, error]);
});
});
| {
"end_byte": 2803,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.catch.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts_0_7343 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {from, interval, Observable, of} from 'rxjs';
import {
elementAt,
every,
filter,
find,
findIndex,
first,
flatMap,
groupBy,
ignoreElements,
isEmpty,
last,
map,
mapTo,
max,
min,
reduce,
repeat,
scan,
single,
skip,
skipUntil,
skipWhile,
startWith,
} from 'rxjs/operators';
import {asyncTest, isPhantomJS} from '../test-util';
describe('Observable.collection', () => {
let log: any[];
let observable1: Observable<any>;
let defaultTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
beforeEach(() => {
log = [];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = defaultTimeout;
});
it('elementAt func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(elementAt(1));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
},
);
});
});
it('every func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const everyZone1: Zone = Zone.current.fork({name: 'Every Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = everyZone1.run(() => {
return observable1.pipe(
every((v: any) => {
expect(Zone.current.name).toEqual(everyZone1.name);
return v % 2 === 0;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([false, 'completed']);
},
);
});
});
it('filter func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const filterZone1: Zone = Zone.current.fork({name: 'Filter Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = filterZone1.run(() => {
return observable1.pipe(
filter((v: any) => {
expect(Zone.current.name).toEqual(filterZone1.name);
return v % 2 === 0;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
},
);
});
});
it('find func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const findZone1: Zone = Zone.current.fork({name: 'Find Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = findZone1.run(() => {
return observable1.pipe(
find((v: any) => {
expect(Zone.current.name).toEqual(findZone1.name);
return v === 2;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
},
);
});
});
it('findIndex func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const findZone1: Zone = Zone.current.fork({name: 'Find Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = findZone1.run(() => {
return observable1.pipe(
findIndex((v: any) => {
expect(Zone.current.name).toEqual(findZone1.name);
return v === 2;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 'completed']);
},
);
});
});
it('first func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const firstZone1: Zone = Zone.current.fork({name: 'First Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = firstZone1.run(() => {
return observable1.pipe(
first((v: any) => {
expect(Zone.current.name).toEqual(firstZone1.name);
return v === 2;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
},
);
});
}); | {
"end_byte": 7343,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts_7347_14673 | it('groupBy func callback should run in the correct zone', () => {
if (isPhantomJS()) {
return;
}
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const groupByZone1: Zone = Zone.current.fork({name: 'groupBy Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
const people = [
{name: 'Sue', age: 25},
{name: 'Joe', age: 30},
{name: 'Frank', age: 25},
{name: 'Sarah', age: 35},
];
return from(people);
});
observable1 = groupByZone1.run(() => {
return observable1.pipe(
groupBy((person: any) => {
expect(Zone.current.name).toEqual(groupByZone1.name);
return person.age;
}),
// return as array of each group
flatMap((group: any) => {
return group.pipe(reduce((acc: any, curr: any) => [...acc, curr], []));
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error' + err);
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([
[
{age: 25, name: 'Sue'},
{age: 25, name: 'Frank'},
],
[{age: 30, name: 'Joe'}],
[{age: 35, name: 'Sarah'}],
'completed',
]);
},
);
});
});
it('ignoreElements func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const ignoreZone1: Zone = Zone.current.fork({name: 'Ignore Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(ignoreElements());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
fail('should not call next');
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['completed']);
},
);
});
});
it('isEmpty func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const isEmptyZone1: Zone = Zone.current.fork({name: 'IsEmpty Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(isEmpty());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([false, 'completed']);
},
);
});
});
it('last func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const lastZone1: Zone = Zone.current.fork({name: 'Last Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(last());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([3, 'completed']);
},
);
});
});
it('map func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const mapZone1: Zone = Zone.current.fork({name: 'Map Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = mapZone1.run(() => {
return observable1.pipe(
map((v: any) => {
expect(Zone.current.name).toEqual(mapZone1.name);
return v + 1;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 3, 4, 'completed']);
},
);
});
});
it('mapTo func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const mapToZone1: Zone = Zone.current.fork({name: 'MapTo Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(1, 2, 3);
});
observable1 = mapToZone1.run(() => {
return observable1.pipe(mapTo('a'));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['a', 'a', 'a', 'completed']);
},
);
});
});
it('max func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(4, 2, 3).pipe(max());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([4, 'completed']);
},
);
});
}); | {
"end_byte": 14673,
"start_byte": 7347,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts_14677_22683 | it('max with comparer func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const maxZone1: Zone = Zone.current.fork({name: 'Max Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(4, 2, 3);
});
observable1 = maxZone1.run(() => {
return observable1.pipe(
max((x: number, y: number) => {
expect(Zone.current.name).toEqual(maxZone1.name);
return x < y ? -1 : 1;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([4, 'completed']);
},
);
});
});
it('min func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(4, 2, 3).pipe(min());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
},
);
});
});
it('min with comparer func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const minZone1: Zone = Zone.current.fork({name: 'Min Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return of(4, 2, 3);
});
observable1 = minZone1.run(() => {
return observable1.pipe(
max((x: number, y: number) => {
expect(Zone.current.name).toEqual(minZone1.name);
return x < y ? 1 : -1;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
},
);
});
});
it('reduce func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const reduceZone1: Zone = Zone.current.fork({name: 'Min Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(4, 2, 3);
});
observable1 = reduceZone1.run(() => {
return observable1.pipe(
reduce((acc: number, one: number) => {
expect(Zone.current.name).toEqual(reduceZone1.name);
return acc + one;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([9, 'completed']);
},
);
});
});
it('scan func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const scanZone1: Zone = Zone.current.fork({name: 'Min Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(4, 2, 3);
});
observable1 = scanZone1.run(() => {
return observable1.pipe(
scan((acc: number, one: number) => {
expect(Zone.current.name).toEqual(scanZone1.name);
return acc + one;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([4, 6, 9, 'completed']);
},
);
});
});
it('repeat func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1).pipe(repeat(2));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 1, 'completed']);
},
);
});
});
it('single func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const singleZone1: Zone = Zone.current.fork({name: 'Single Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3, 4, 5);
});
observable1 = singleZone1.run(() => {
return observable1.pipe(
single((val: any) => {
expect(Zone.current.name).toEqual(singleZone1.name);
return val === 4;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([4, 'completed']);
},
);
});
});
it('skip func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3, 4, 5).pipe(skip(3));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([4, 5, 'completed']);
},
);
});
}); | {
"end_byte": 22683,
"start_byte": 14677,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts_22687_25598 | xit(
'skipUntil func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10).pipe(skipUntil(interval(25)));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
subscriber.unsubscribe();
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([2, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'skipWhile func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const skipZone1: Zone = Zone.current.fork({name: 'Skip Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10);
});
observable1 = skipZone1.run(() => {
return observable1.pipe(
skipWhile((val: any) => {
expect(Zone.current.name).toEqual(skipZone1.name);
return val < 2;
}),
);
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
subscriber.unsubscribe();
expect(result).toEqual(2);
done();
},
(err: any) => {
fail('should not call error');
},
);
});
}, Zone.root),
);
it('startWith func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2).pipe(startWith(3));
});
subscriptionZone.run(() => {
const subscriber = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([3, 1, 2, 'completed']);
},
);
});
});
}); | {
"end_byte": 25598,
"start_byte": 22687,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.collection.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.zip.spec.ts_0_1539 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {of, range, zip} from 'rxjs';
describe('Observable.zip', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
beforeEach(() => {
log = [];
});
it('zip func callback should run in the correct zone', () => {
const observable1: any = constructorZone1.run(() => {
return range(1, 3);
});
const observable2: any = constructorZone1.run(() => {
return of('foo', 'bar', 'beer');
});
const observable3: any = constructorZone1.run(() => {
return zip(observable1, observable2, function (n: number, str: string) {
expect(Zone.current.name).toEqual(constructorZone1.name);
return {n: n, str: str};
});
});
subscriptionZone.run(() => {
observable3.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([{n: 1, str: 'foo'}, {n: 2, str: 'bar'}, {n: 3, str: 'beer'}, 'completed']);
});
});
| {
"end_byte": 1539,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.zip.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.bindNodeCallback.spec.ts_0_3452 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {asapScheduler, bindCallback, bindNodeCallback, Observable} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.bindNodeCallback', () => {
let log: any[];
const constructorZone: Zone = Zone.root.fork({name: 'Constructor Zone'});
const subscriptionZone: Zone = Zone.root.fork({name: 'Subscription Zone'});
let func: any;
let boundFunc: any;
let observable: any;
beforeEach(() => {
log = [];
});
it('bindNodeCallback func callback should run in the correct zone', () => {
constructorZone.run(() => {
func = function (arg: any, callback: (error: any, result: any) => any) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(null, arg);
};
boundFunc = bindNodeCallback(func);
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe((arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
});
});
expect(log).toEqual(['nexttest']);
});
it('bindNodeCallback with selector should run in correct zone', () => {
constructorZone.run(() => {
func = function (arg: any, callback: (error: any, result: any) => any) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(null, arg);
};
boundFunc = bindNodeCallback(func, (arg: any) => {
expect(Zone.current.name).toEqual(constructorZone.name);
return 'selector' + arg;
});
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe((arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
});
});
expect(log).toEqual(['nextselectortest']);
});
it(
'bindNodeCallback with async scheduler should run in correct zone',
asyncTest((done: any) => {
constructorZone.run(() => {
func = function (arg: any, callback: (error: any, result: any) => any) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(null, arg);
};
boundFunc = bindCallback(func, () => true, asapScheduler);
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe((arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
done();
});
});
expect(log).toEqual([]);
}),
);
it('bindNodeCallback call with error should run in correct zone', () => {
constructorZone.run(() => {
func = function (arg: any, callback: (error: any, result: any) => any) {
expect(Zone.current.name).toEqual(constructorZone.name);
callback(arg, null);
};
boundFunc = bindCallback(func);
observable = boundFunc('test');
});
subscriptionZone.run(() => {
observable.subscribe(
(arg: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('next' + arg);
},
(error: any) => {
log.push('error' + error);
},
);
});
expect(log).toEqual(['nexttest,']);
});
});
| {
"end_byte": 3452,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.bindNodeCallback.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.spec.ts_0_1938 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
(Object as any).setPrototypeOf =
(Object as any).setPrototypeOf ||
function (obj: any, proto: any) {
obj.__proto__ = proto;
return obj;
};
import '../../lib/rxjs/rxjs';
import './rxjs.common.spec';
import './rxjs.asap.spec';
import './rxjs.bindCallback.spec';
import './rxjs.bindNodeCallback.spec';
import './rxjs.combineLatest.spec';
import './rxjs.concat.spec';
import './rxjs.defer.spec';
import './rxjs.empty.spec';
import './rxjs.forkjoin.spec';
import './rxjs.from.spec';
import './rxjs.fromEvent.spec';
import './rxjs.fromPromise.spec';
import './rxjs.interval.spec';
import './rxjs.merge.spec';
import './rxjs.never.spec';
import './rxjs.of.spec';
import './rxjs.range.spec';
import './rxjs.retry.spec';
import './rxjs.throw.spec';
import './rxjs.timer.spec';
import './rxjs.zip.spec';
import './rxjs.Observable.audit.spec';
import './rxjs.Observable.buffer.spec';
import './rxjs.Observable.catch.spec';
import './rxjs.Observable.combine.spec';
import './rxjs.Observable.concat.spec';
import './rxjs.Observable.count.spec';
import './rxjs.Observable.debounce.spec';
import './rxjs.Observable.default.spec';
import './rxjs.Observable.delay.spec';
import './rxjs.Observable.notification.spec';
import './rxjs.Observable.distinct.spec';
import './rxjs.Observable.do.spec';
import './rxjs.Observable.collection.spec';
// // TODO: @JiaLiPassion, add exhaust test
import './rxjs.Observable.merge.spec';
import './rxjs.Observable.multicast.spec';
import './rxjs.Observable.map.spec';
import './rxjs.Observable.race.spec';
import './rxjs.Observable.sample.spec';
import './rxjs.Observable.take.spec';
import './rxjs.Observable.retry.spec';
import './rxjs.Observable.timeout.spec';
import './rxjs.Observable.window.spec';
| {
"end_byte": 1938,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.concat.spec.ts_0_3083 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {asapScheduler, concat, Observable, range} from 'rxjs';
import {asyncTest} from '../test-util';
describe('Observable.concat', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const constructorZone3: Zone = Zone.current.fork({name: 'Constructor Zone3'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
let observable2: any;
let concatObservable: any;
beforeEach(() => {
log = [];
});
it('concat func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return new Observable((subscriber) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
});
observable2 = constructorZone2.run(() => {
return range(3, 4);
});
constructorZone3.run(() => {
concatObservable = concat(observable1, observable2);
});
subscriptionZone.run(() => {
concatObservable.subscribe((concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
});
});
expect(log).toEqual([1, 2, 3, 4, 5, 6]);
});
it(
'concat func callback should run in the correct zone with scheduler',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const constructorZone3: Zone = Zone.current.fork({name: 'Constructor Zone3'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return new Observable((subscriber) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
});
observable2 = constructorZone2.run(() => {
return range(3, 4);
});
constructorZone3.run(() => {
concatObservable = concat(observable1, observable2, asapScheduler);
});
subscriptionZone.run(() => {
concatObservable.subscribe(
(concat: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(concat);
},
(error: any) => {
fail('subscribe failed' + error);
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 2, 3, 4, 5, 6]);
done();
},
);
});
expect(log).toEqual([]);
}, Zone.root),
);
});
| {
"end_byte": 3083,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.concat.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.count.spec.ts_0_1344 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, range} from 'rxjs';
import {count} from 'rxjs/operators';
describe('Observable.count', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('count func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return range(1, 3).pipe(
count((i: number) => {
expect(Zone.current.name).toEqual(constructorZone1.name);
return i % 2 === 0;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
);
});
expect(log).toEqual([1, 'completed']);
});
});
| {
"end_byte": 1344,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.count.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.util.ts_0_411 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function supportFeature(Observable: any, method: string) {
const func = function () {
return !!Observable.prototype[method];
};
(func as any).message = `Observable.${method} not support`;
}
| {
"end_byte": 411,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.util.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.window.spec.ts_0_5418 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, Observable, timer} from 'rxjs';
import {mergeAll, take, window, windowCount, windowToggle, windowWhen} from 'rxjs/operators';
import {asyncTest} from '../test-util';
// @JiaLiPassion, in Safari 9(iOS 9), the case is not
// stable because of the timer, try to fix it later
xdescribe('Observable.window', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'window func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
const source = timer(0, 10).pipe(take(6));
const w = source.pipe(window(interval(30)));
return w.pipe(mergeAll());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 3, 4, 5, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'windowCount func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
const source = timer(0, 10).pipe(take(10));
const window = source.pipe(windowCount(4));
return window.pipe(mergeAll());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'windowToggle func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const windowZone1: Zone = Zone.current.fork({name: 'Window Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return timer(0, 10).pipe(take(10));
});
windowZone1.run(() => {
return observable1.pipe(
windowToggle(interval(30), (val: any) => {
expect(Zone.current.name).toEqual(windowZone1.name);
return interval(15);
}),
mergeAll(),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'windowWhen func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const windowZone1: Zone = Zone.current.fork({name: 'Window Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
return timer(0, 10).pipe(take(10));
});
windowZone1.run(() => {
return observable1.pipe(
windowWhen(() => {
expect(Zone.current.name).toEqual(windowZone1.name);
return interval(15);
}),
mergeAll(),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 5418,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.window.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.notification.spec.ts_0_1912 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Notification, Observable, of} from 'rxjs';
import {dematerialize} from 'rxjs/operators';
import {asyncTest, ifEnvSupports} from '../test-util';
const supportNotification = function () {
return typeof Notification !== 'undefined';
};
(supportNotification as any).message = 'RxNotification';
describe(
'Observable.notification',
ifEnvSupports(supportNotification, () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('notification func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
const error = new Error('test');
observable1 = constructorZone1.run(() => {
const notifA = new Notification('N' as any, 'A');
const notifB = new Notification('N' as any, 'B');
const notifE = new Notification('E' as any, void 0, error);
const materialized = of(notifA, notifB, notifE as any);
return materialized.pipe(dematerialize());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
log.push(err);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['A', 'B', error]);
},
);
});
});
}),
);
| {
"end_byte": 1912,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.notification.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.defer.spec.ts_0_1318 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {defer, Observable} from 'rxjs';
describe('Observable.defer', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('defer func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return defer(() => {
return new Observable<number>((subscribe) => {
log.push('setup');
expect(Zone.current.name).toEqual(constructorZone1.name);
subscribe.next(1);
subscribe.complete();
return () => {
expect(Zone.current.name).toEqual(constructorZone1.name);
log.push('cleanup');
};
});
});
});
subscriptionZone.run(() => {
observable1.subscribe((result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
});
});
expect(log).toEqual(['setup', 1, 'cleanup']);
});
});
| {
"end_byte": 1318,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.defer.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.take.spec.ts_0_4440 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, Observable, of} from 'rxjs';
import {take, takeLast, takeUntil, takeWhile} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.take', () => {
let log: any[];
let observable1: Observable<any>;
let defaultTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
beforeEach(() => {
log = [];
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = defaultTimeout;
});
it('take func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(take(1));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([1, 'completed']);
},
);
});
});
it('takeLast func callback should run in the correct zone', () => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(takeLast(1));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([3, 'completed']);
},
);
});
});
xit(
'takeUntil func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10).pipe(takeUntil(interval(25)));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 'completed']);
done();
},
);
});
}, Zone.root),
);
it(
'takeWhile func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const takeZone1: Zone = Zone.current.fork({name: 'Take Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return interval(10);
});
observable1 = takeZone1.run(() => {
return observable1.pipe(
takeWhile((val: any) => {
expect(Zone.current.name).toEqual(takeZone1.name);
return val < 2;
}),
);
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual([0, 1, 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 4440,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.take.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.map.spec.ts_0_3349 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable, observable, of} from 'rxjs';
import {pairwise, partition, pluck} from 'rxjs/operators';
import {ifEnvSupports} from '../test-util';
import {supportFeature} from './rxjs.util';
describe('Observable.map', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it('pairwise func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return of(1, 2, 3).pipe(pairwise());
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual([[1, 2], [2, 3], 'completed']);
});
it('partition func callback should run in the correct zone', () => {
const partitionZone = Zone.current.fork({name: 'Partition Zone1'});
const observable1: any = constructorZone1.run(() => {
return of(1, 2, 3);
});
const part: any = partitionZone.run(() => {
return observable1.pipe(
partition((val: any) => {
expect(Zone.current.name).toEqual(partitionZone.name);
return val % 2 === 0;
}),
);
});
subscriptionZone.run(() => {
part[0].subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('first' + result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
part[1].subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('second' + result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual(['first2', 'completed', 'second1', 'second3', 'completed']);
});
it('pluck func callback should run in the correct zone', () => {
observable1 = constructorZone1.run(() => {
return of({a: 1, b: 2}, {a: 3, b: 4}).pipe(pluck('a'));
});
subscriptionZone.run(() => {
observable1.subscribe(
(result: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(result);
},
() => {
fail('should not call error');
},
() => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push('completed');
},
);
});
expect(log).toEqual([1, 3, 'completed']);
});
});
| {
"end_byte": 3349,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.map.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.Observable.race.spec.ts_0_1479 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {interval, Observable, race} from 'rxjs';
import {mapTo} from 'rxjs/operators';
import {asyncTest} from '../test-util';
describe('Observable.race', () => {
let log: any[];
let observable1: Observable<any>;
beforeEach(() => {
log = [];
});
it(
'race func callback should run in the correct zone',
asyncTest((done: any) => {
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
observable1 = constructorZone1.run(() => {
return race(interval(10).pipe(mapTo('a')), interval(15).pipe(mapTo('b')));
});
subscriptionZone.run(() => {
const subscriber: any = observable1.subscribe(
(result: any) => {
log.push(result);
expect(Zone.current.name).toEqual(subscriptionZone.name);
subscriber.complete();
},
(err: any) => {
fail('should not call error');
},
() => {
log.push('completed');
expect(Zone.current.name).toEqual(subscriptionZone.name);
expect(log).toEqual(['a', 'completed']);
done();
},
);
});
}, Zone.root),
);
});
| {
"end_byte": 1479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.Observable.race.spec.ts"
} |
angular/packages/zone.js/test/rxjs/rxjs.combineLatest.spec.ts_0_3005 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {combineLatest, Observable} from 'rxjs';
describe('Observable.combineLatest', () => {
let log: any[];
const constructorZone1: Zone = Zone.current.fork({name: 'Constructor Zone1'});
const constructorZone2: Zone = Zone.current.fork({name: 'Constructor Zone2'});
const constructorZone3: Zone = Zone.current.fork({name: 'Constructor Zone3'});
const subscriptionZone: Zone = Zone.current.fork({name: 'Subscription Zone'});
let observable1: Observable<any>;
let observable2: any;
let subscriber1: any;
let subscriber2: any;
let combinedObservable: any;
beforeEach(() => {
log = [];
});
it('combineLatest func should run in the correct zone', () => {
observable1 = constructorZone1.run(
() =>
new Observable((_subscriber) => {
subscriber1 = _subscriber;
expect(Zone.current.name).toEqual(constructorZone1.name);
log.push('setup1');
}),
);
observable2 = constructorZone2.run(
() =>
new Observable((_subscriber) => {
subscriber2 = _subscriber;
expect(Zone.current.name).toEqual(constructorZone2.name);
log.push('setup2');
}),
);
constructorZone3.run(() => {
combinedObservable = combineLatest(observable1, observable2);
});
subscriptionZone.run(() => {
combinedObservable.subscribe((combined: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(combined);
});
});
subscriber1.next(1);
subscriber2.next(2);
subscriber2.next(3);
expect(log).toEqual(['setup1', 'setup2', [1, 2], [1, 3]]);
});
it('combineLatest func with project function should run in the correct zone', () => {
observable1 = constructorZone1.run(
() =>
new Observable((_subscriber) => {
subscriber1 = _subscriber;
expect(Zone.current.name).toEqual(constructorZone1.name);
log.push('setup1');
}),
);
observable2 = constructorZone2.run(
() =>
new Observable((_subscriber) => {
subscriber2 = _subscriber;
expect(Zone.current.name).toEqual(constructorZone2.name);
log.push('setup2');
}),
);
constructorZone3.run(() => {
combinedObservable = combineLatest(observable1, observable2, (x: number, y: number) => {
expect(Zone.current.name).toEqual(constructorZone3.name);
return x + y;
});
});
subscriptionZone.run(() => {
combinedObservable.subscribe((combined: any) => {
expect(Zone.current.name).toEqual(subscriptionZone.name);
log.push(combined);
});
});
subscriber1.next(1);
subscriber2.next(2);
subscriber2.next(3);
expect(log).toEqual(['setup1', 'setup2', 3, 4]);
});
});
| {
"end_byte": 3005,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/test/rxjs/rxjs.combineLatest.spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.