Skip to content

Commit

Permalink
Merge pull request #755 from Polymer/wct-mocha-typings
Browse files Browse the repository at this point in the history
Get wct-mocha compiling clean.
  • Loading branch information
rictic authored Oct 25, 2018
2 parents 4ff61dc + 9e0cb58 commit fbc1a8f
Show file tree
Hide file tree
Showing 18 changed files with 130 additions and 106 deletions.
20 changes: 10 additions & 10 deletions packages/wct-mocha/src/childrunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ export default class ChildRunner {
private container?: HTMLDivElement;
private eventListenersToRemoveOnClean: EventListenerDescriptor[] = [];
private iframe?: HTMLIFrameElement;
private onRunComplete: (error?: {}) => void;
private share: SharedState;
private state: 'initializing'|'loading'|'complete';
private onRunComplete: ((error?: {}) => void)|null = null;
share: SharedState|null = null;
state: 'initializing'|'loading'|'complete';
private timeoutId?: number;
private url: string;

Expand Down Expand Up @@ -88,7 +88,7 @@ export default class ChildRunner {
* @return {ChildRunner} The `ChildRunner` that was registered for this
* window.
*/
static current(): ChildRunner {
static current(): ChildRunner|null {
return ChildRunner.get(window);
}

Expand All @@ -97,7 +97,7 @@ export default class ChildRunner {
* @param {boolean} traversal Whether this is a traversal from a child window.
* @return {ChildRunner} The `ChildRunner` that was registered for `target`.
*/
static get(target: Window, traversal?: boolean): ChildRunner {
static get(target: Window, traversal?: boolean): ChildRunner|null {
const childRunner = ChildRunner.byUrl[target.location.href];
if (childRunner) {
return childRunner;
Expand Down Expand Up @@ -154,7 +154,7 @@ export default class ChildRunner {
() => this.loaded(new Error('Failed to load document ' + this.url)),
iframe);
this.addEventListener(
'DOMContentLoaded', () => this.loaded(), iframe.contentWindow);
'DOMContentLoaded', () => this.loaded(), iframe.contentWindow!);
}

/**
Expand All @@ -165,15 +165,15 @@ export default class ChildRunner {
loaded(error?: {}) {
util.debug('ChildRunner#loaded', this.url, error);

if (this.iframe.contentWindow == null && error) {
if (!this.iframe || this.iframe.contentWindow == null && error) {
this.signalRunComplete(error);
this.done();
return;
}

// Not all targets have WCT loaded (compatiblity mode)
if (this.iframe.contentWindow.WCT) {
this.share = this.iframe.contentWindow.WCT.share;
if (this.iframe.contentWindow!.WCT) {
this.share = this.iframe.contentWindow!.WCT.share;
}

if (error) {
Expand Down Expand Up @@ -215,7 +215,7 @@ export default class ChildRunner {
setTimeout(() => {
this.removeAllEventListeners();

this.container.removeChild(this.iframe as Node);
this.container!.removeChild(this.iframe as Node);
this.iframe = undefined;
this.share = null;
}, 0);
Expand Down
6 changes: 3 additions & 3 deletions packages/wct-mocha/src/clisocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export default class CLISocket {
*
* @param {function(*, CLISocket)} done Node-style callback.
*/
static init(done: (error?: {}, socket?: CLISocket) => void) {
static init(done: (error?: {}|null|undefined, socket?: CLISocket) => void) {
const browserId = util.getParam('cli_browser_id');
if (!browserId) {
return done();
Expand All @@ -108,7 +108,7 @@ export default class CLISocket {
return done();
}

util.loadScript(SOCKETIO_LIBRARY, (error: {}) => {
util.loadScript(SOCKETIO_LIBRARY, (error: {}|undefined|null) => {
if (error) {
return done(error);
}
Expand Down Expand Up @@ -139,7 +139,7 @@ export default class CLISocket {
* @return {!Array.<string>} The titles of the runnable and its parents.
*/
function getTitles(runnable: Mocha.IRunnable) {
const titles = [];
const titles: string[] = [];
while (runnable && !runnable.root && runnable.title) {
titles.unshift(runnable.title);
runnable = runnable.parent as {} as Mocha.IRunnable;
Expand Down
14 changes: 8 additions & 6 deletions packages/wct-mocha/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function setup(options: Partial<Config>) {
const wctMochaJsRoot = util.scriptPrefix('wct-mocha.js');
const browserJsRoot = util.scriptPrefix('browser.js');
const scriptName = wctMochaJsRoot ? 'wct-mocha.js' : 'browser.js';
const root = wctMochaJsRoot || browserJsRoot;
const root = (wctMochaJsRoot || browserJsRoot)!;
_config.root = util.basePath(root.substr(0, root.length - 1));
if (!_config.root) {
throw new Error(
Expand All @@ -93,11 +93,13 @@ export function get<K extends keyof Config>(key: K): Config[K] {
return _config[key];
}

export function deepMerge(target: Partial<Config>, source: Partial<Config>) {
Object.keys(source).forEach((key) => {
if (target[key] !== null && typeof target[key] === 'object' &&
!Array.isArray(target[key])) {
deepMerge(target[key], source[key]);
export function deepMerge<V extends {}>(target: V, source: V) {
Object.keys(source).forEach((untypedKey) => {
const key = untypedKey as keyof typeof source;
const targetValue = target[key];
if (targetValue != null && typeof targetValue === 'object' &&
!Array.isArray(targetValue)) {
deepMerge(targetValue, source[key]);
} else {
target[key] = source[key];
}
Expand Down
4 changes: 2 additions & 2 deletions packages/wct-mocha/src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ export function loadSync() {
scripts.push(a11ySuiteScriptPath);
}
scripts.forEach((path) => {
const url = util.expandUrl(path, config.get('root'));
const url = util.expandUrl(path, config.get('root')!);
util.debug('Loading environment script:', url);
// Synchronous load.
document.write(`<script src="${encodeURI(url)}"></script>`);
});
util.debug('Environment scripts loaded');
const imports = config.get('environmentImports');
imports.forEach((path) => {
const url = util.expandUrl(path, config.get('root'));
const url = util.expandUrl(path, config.get('root')!);
util.debug('Loading environment import:', url);
// Synchronous load.
document.write(`<link rel="import" href="${encodeURI(url)}">`);
Expand Down
2 changes: 1 addition & 1 deletion packages/wct-mocha/src/environment/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ export function flush(callback: () => void) {
} else if (window.WebComponents && window.WebComponents.flush) {
scope = window.WebComponents;
}
if (scope) {
if (scope && scope.flush) {
scope.flush();
}

Expand Down
2 changes: 1 addition & 1 deletion packages/wct-mocha/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function initialize(initConfig?: config.Config) {
// Until then, we get to rely on it to expose parent runners to their
// children.
_ChildRunner: ChildRunner,
_reporter: undefined as MultiReporter, // assigned below
_reporter: undefined! as MultiReporter, // assigned below
_config: config._config,

// Public API
Expand Down
31 changes: 20 additions & 11 deletions packages/wct-mocha/src/mocha/extend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ export function extendInterfaces(
interfaceExtensions.push(() => {
const Mocha = window.Mocha;
// For all Mocha interfaces (probably just TDD and BDD):
Object.keys(Mocha.interfaces).forEach((interfaceName: 'tdd'|'bdd') => {
Object.keys(Mocha.interfaces).forEach((interfaceName: string) => {
if (interfaceName !== 'tdd' && interfaceName !== 'bdd') {
return;
}
// This is the original callback that defines the interface (TDD or
// BDD):
const originalInterface = Mocha.interfaces[interfaceName];
Expand All @@ -44,16 +47,22 @@ export function extendInterfaces(
originalInterface.apply(this, arguments);
// Register a listener so that we can further extend the base
// interface:
suite.on('pre-require', (context: {}, _file: string, _mocha: {}) => {
// Capture a bound reference to the teardown function as a
// convenience:
const teardown = context[teardownProperty].bind(context);
// Add our new helper to the testing context. The helper is
// generated by a factory method that receives the context,
// the teardown function and the interface name and returns
// the new method to be added to that context:
context[helperName] = helperFactory(context, teardown, interfaceName);
});
suite.on(
'pre-require',
(context: {teardown: Function, afterEach: Function},
_file: string,
_mocha: {}) => {
// Capture a bound reference to the teardown function as a
// convenience:
const teardown = context[teardownProperty].bind(context);
// Add our new helper to the testing context. The helper is
// generated by a factory method that receives the context,
// the teardown function and the interface name and returns
// the new method to be added to that context:
// tslint:disable-next-line:no-any
(context as any)[helperName] =
helperFactory(context, teardown, interfaceName);
});
};
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/wct-mocha/src/reporters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ export let jsSuites: Array<undefined> = [];
* @return {!Array.<!Mocha.reporters.Base} The reporters that should be used.
*/
export function determineReporters(
socket: CLISocket, parent: MultiReporter): ReporterFactory[] {
socket: CLISocket, parent: MultiReporter|null): ReporterFactory[] {
// Parents are greedy.
if (parent) {
return [parent.childReporter(window.location)];
return [parent.childReporter()];
}

// Otherwise, we get to run wild without any parental supervision!
Expand Down
11 changes: 9 additions & 2 deletions packages/wct-mocha/src/reporters/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,25 @@ const CAN_STYLE_GROUP = userAgent.match('webkit');
// Track the indent for faked `console.group`
let logIndent = '';

function getStyle(style?: keyof typeof STYLES): string {
if (style === undefined) {
return STYLES.plain;
}
return STYLES[style] || STYLES.plain;
}

function log(text: string, style?: keyof typeof STYLES) {
text = text.split('\n').map((l) => logIndent + l).join('\n');
if (CAN_STYLE_LOG) {
console.log('%c' + text, STYLES[style] || STYLES.plain);
console.log('%c' + text, getStyle(style));
} else {
console.log(text);
}
}

function logGroup(text: string, style?: keyof typeof STYLES) {
if (CAN_STYLE_GROUP) {
console.group('%c' + text, STYLES[style] || STYLES.plain);
console.group('%c' + text, getStyle(style));
} else if (console.group) {
console.group(text);
} else {
Expand Down
6 changes: 3 additions & 3 deletions packages/wct-mocha/src/reporters/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
*
* @param {!Mocha.Runner} runner The runner that is being reported on.
*/
export default function HTML(runner: Mocha.IRunner) {
export default function HTML(this: Mocha.IRunner, runner: Mocha.IRunner) {
const output = document.createElement('div');
output.id = 'mocha';
document.body.appendChild(output);

runner.on('suite', function(_test: {}) {
runner.on('suite', function(this: Mocha.IRunner, _test: {}) {
this.total = runner.total;
}.bind(this));

Expand Down Expand Up @@ -67,4 +67,4 @@ style.textContent = `
color: #555 !important;
}
`;
document.head.appendChild(style);
document.head!.appendChild(style);
14 changes: 6 additions & 8 deletions packages/wct-mocha/src/reporters/multi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,16 @@ export interface ReporterFactory {
}

interface ExtendedTest extends Mocha.ITest {
err: {};
err: {}|undefined;
}

/**
* A Mocha-like reporter that combines the output of multiple Mocha suites.
*/
export default class MultiReporter implements Reporter {
private readonly reporters: ReadonlyArray<Reporter>;
private readonly parent: MultiReporter|undefined;
private readonly basePath: string;
readonly reporters: ReadonlyArray<Reporter>;
readonly parent: MultiReporter|undefined|null;
readonly basePath: string;
total: number;
private currentRunner: null|Mocha.IRunner;
/** Arguments that would be called on emit(). */
Expand All @@ -73,7 +73,7 @@ export default class MultiReporter implements Reporter {
*/
constructor(
numSuites: number, reporters: ReporterFactory[],
parent: MultiReporter|undefined) {
parent: MultiReporter|undefined|null) {
this.reporters = reporters.map((reporter) => {
return new reporter(this);
});
Expand All @@ -92,12 +92,10 @@ export default class MultiReporter implements Reporter {
}

/**
* @param location The location this reporter represents.
* @return A reporter-like "class" for each child suite
* that should be passed to `mocha.run`.
*/
childReporter(location: Location|string): ReporterFactory {
const name = this.suiteTitle(location);
childReporter(): ReporterFactory {
// The reporter is used as a constructor, so we can't depend on `this` being
// properly bound.
const self = this;
Expand Down
9 changes: 4 additions & 5 deletions packages/wct-mocha/src/reporters/title.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ const ARC_WIDTH = 6;
* @param {!Mocha.Runner} runner The runner that is being reported on.
*/
export default class Title {
runner: Mocha.Runner;
constructor(runner: Mocha.IRunner) {
Mocha.reporters.Base.call(this, runner);

Expand All @@ -46,7 +45,7 @@ export default class Title {
updateFavicon() {
const canvas = document.createElement('canvas');
canvas.height = canvas.width = 32;
const context = canvas.getContext('2d');
const context = canvas.getContext('2d')!;

const passing = this.stats.passes;
const pending = this.stats.pending;
Expand All @@ -61,17 +60,17 @@ export default class Title {

/** Sets the current favicon by URL. */
setFavicon(url: string) {
const current = document.head.querySelector('link[rel="icon"]');
const current = document.head!.querySelector('link[rel="icon"]');
if (current) {
document.head.removeChild(current as Node);
document.head!.removeChild(current as Node);
}

const link = document.createElement('link');
link.rel = 'icon';
link.type = 'image/x-icon';
link.href = url;
link.setAttribute('sizes', '32x32');
document.head.appendChild(link);
document.head!.appendChild(link);
}
}

Expand Down
Loading

0 comments on commit fbc1a8f

Please sign in to comment.