* @fileoverview Javascript test harness.
*/
import type {TaskTimer} from '//ios/web/annotations/resources/text_tasks.js';
export class FakeTaskTimer implements TaskTimer {
nowMs = 0;
timers = new Map<number, {then: Function, at: number}>();
uniqueId = 0;
clear(id: number): void {
this.timers.delete(id);
}
reset(then: Function, ms: number): number {
const id = ++this.uniqueId;
this.timers.set(id, {then, at: this.now() + ms});
return id;
}
now(): number {
return this.nowMs;
}
nextEventId(): number|null {
let next: number|null = null;
this.timers.forEach((value, key) => {
if (next === null || value.at < this.timers.get(next)!.at) {
next = key;
}
});
return next;
}
moveAhead(ms: number, times = 1): void {
while (times > 0) {
this.nowMs += ms;
let next = this.nextEventId();
while (next) {
const event = this.timers.get(next)!;
if (event.at > this.nowMs) {
break;
}
this.timers.delete(next);
event.then();
next = this.nextEventId();
}
times--;
}
}
restart() {
this.nowMs = 0;
this.timers.clear();
}
}
interface TestResult {
name: string;
result: string;
error?: string;
}
export class TestSuite {
private results: TestResult[] = [];
setUpSuite(): void {
document.body.innerHTML = '';
document.head.innerHTML = '';
}
setUp(): void {}
run(): TestResult[] {
this.results = [];
const tryPhase = (phase: string, callback: Function) => {
try {
callback();
} catch (error) {
this.results.push({
name: phase,
result: 'FAILED',
error: '' + error + '\n' + (error as Error).stack,
});
}
};
tryPhase('setUpSuite', () => {
this.setUpSuite();
});
for (const method of Object.getOwnPropertyNames(
Object.getPrototypeOf(this))) {
if (method.startsWith('test')) {
tryPhase('setUp(' + method + ')', () => {
this.setUp();
});
tryPhase(method, () => {
(this as any)[method]();
this.results.push({name: method, result: 'OK'});
});
tryPhase('tearDown(' + method + ')', () => {
this.tearDown();
});
}
}
tryPhase('tearDownSuite', () => {
this.tearDownSuite();
});
return this.results;
}
tearDown(): void {}
tearDownSuite(): void {}
log(data: any): void {
this.results.push({name: 'log', result: 'LOG', error: '' + data});
}
}
export function expectEq(a: any, b: any, info = ''): void {
if (a !== b) {
throw new Error(info + `"${a}" !== "${b}"`);
}
}
export function expectNeq(a: any, b: any, info = ''): void {
if (a === b) {
throw new Error(info + `"${a}" === "${b}"`);
}
}
export function fail(info = ''): void {
throw new Error(info);
}
export function load(html: string): void {
document.body.innerHTML = html;
}
export function loadHead(html: string): void {
document.head.innerHTML = html;
}