deno/cli/tests/unit/dom_iterable_test.ts

92 lines
2.4 KiB
TypeScript
Raw Normal View History

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2020-09-18 13:20:55 +00:00
/* TODO https://github.com/denoland/deno/issues/7540
import { unitTest, assert, assertEquals } from "./test_util.ts";
2018-10-23 11:43:43 +00:00
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
2018-10-23 11:43:43 +00:00
function setup() {
const dataSymbol = Symbol("data symbol");
class Base {
[dataSymbol] = new Map<string, number>();
2018-10-23 11:43:43 +00:00
constructor(
data: Array<[string, number]> | IterableIterator<[string, number]>,
2018-10-23 11:43:43 +00:00
) {
for (const [key, value] of data) {
this[dataSymbol].set(key, value);
}
}
}
return {
Base,
2019-02-13 13:50:15 +00:00
// This is using an internal API we don't want published as types, so having
// to cast to any to "trick" TypeScript
// @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol
DomIterable: Deno[Deno.internal].DomIterableMixin(Base, dataSymbol),
2018-10-23 11:43:43 +00:00
};
}
2020-09-18 13:20:55 +00:00
unitTest(function testDomIterable(): void {
2018-10-23 11:43:43 +00:00
const { DomIterable, Base } = setup();
const fixture: Array<[string, number]> = [
["foo", 1],
["bar", 2],
];
2018-10-23 11:43:43 +00:00
const domIterable = new DomIterable(fixture);
assertEquals(Array.from(domIterable.entries()), fixture);
assertEquals(Array.from(domIterable.values()), [1, 2]);
assertEquals(Array.from(domIterable.keys()), ["foo", "bar"]);
2018-10-23 11:43:43 +00:00
let result: Array<[string, number]> = [];
for (const [key, value] of domIterable) {
assert(key != null);
assert(value != null);
result.push([key, value]);
}
assertEquals(fixture, result);
2018-10-23 11:43:43 +00:00
result = [];
const scope = {};
function callback(
this: typeof scope,
value: number,
key: string,
parent: typeof domIterable,
): void {
assertEquals(parent, domIterable);
2018-10-23 11:43:43 +00:00
assert(key != null);
assert(value != null);
assert(this === scope);
result.push([key, value]);
}
domIterable.forEach(callback, scope);
assertEquals(fixture, result);
2018-10-23 11:43:43 +00:00
assertEquals(DomIterable.name, Base.name);
2018-10-23 11:43:43 +00:00
});
unitTest(function testDomIterableScope(): void {
2018-10-23 11:43:43 +00:00
const { DomIterable } = setup();
const domIterable = new DomIterable([["foo", 1]]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function checkScope(thisArg: any, expected: any): void {
function callback(this: typeof thisArg): void {
assertEquals(this, expected);
2018-10-23 11:43:43 +00:00
}
domIterable.forEach(callback, thisArg);
}
checkScope(0, Object(0));
checkScope("", Object(""));
checkScope(null, window);
checkScope(undefined, window);
});
2020-09-18 13:20:55 +00:00
*/