Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Debug Jest slowless #32

Merged
merged 13 commits into from
Feb 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
],
"settings": {
"node": true
},
"jest": {
"timers": "fake"
}
}
}
17 changes: 9 additions & 8 deletions packages/core/src/Tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@ export interface ToolPluginRegistry {
reporter: Reporter;
}

const translatorCache: Map<Tool<any>, Translator> = new Map();

export default class Tool<
PluginRegistry extends ToolPluginRegistry,
Config extends ToolConfig = ToolConfig
Expand Down Expand Up @@ -98,6 +96,8 @@ export default class Tool<

private pluginTypes: { [K in keyof PluginRegistry]?: PluginType<PluginRegistry[K]> } = {};

private translator: Translator | null = null;

constructor(options: Partial<ToolOptions>, argv: string[] = []) {
super();

Expand Down Expand Up @@ -132,9 +132,6 @@ export default class Tool<
// eslint-disable-next-line global-require
this.debug('Using boost v%s', require('../package.json').version);

// Setup i18n translation
translatorCache.set(this, this.createTranslator());

// Initialize the console first so we can start logging
this.console = new Console(this);

Expand Down Expand Up @@ -535,7 +532,11 @@ export default class Tool<
* Retrieve a translated message from a resource bundle.
*/
msg(key: string | string, params?: { [key: string]: any }, options?: i18next.TOptions): string {
return translatorCache.get(this)!.t(key, {
if (!this.translator) {
this.translator = this.createTranslator();
}

return this.translator.t(key, {
interpolation: { escapeValue: false },
replace: params,
...options,
Expand Down Expand Up @@ -599,8 +600,8 @@ export default class Tool<
}

// Update locale
if (this.config.locale) {
translatorCache.get(this)!.changeLanguage(this.config.locale);
if (this.config.locale && this.translator) {
this.translator.changeLanguage(this.config.locale);
}

return this;
Expand Down
14 changes: 0 additions & 14 deletions packages/core/tests/Console.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@ describe('Console', () => {
stderr: err,
stdout: out,
});

jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

describe('disable()', () => {
Expand Down Expand Up @@ -541,14 +535,6 @@ describe('Console', () => {
});

describe('startRenderLoop()', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('sets a timer', () => {
// @ts-ignore Allow access
expect(cli.renderTimer).toBeNull();
Expand Down
5 changes: 5 additions & 0 deletions packages/core/tests/CrashLogger.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import fs from 'fs-extra';
import path from 'path';
import execa from 'execa';
import { mockTool } from '@boost/test-utils';
import CrashLogger from '../src/CrashLogger';
import Tool from '../src/Tool';

jest.mock('execa');

describe('CrashLogger', () => {
let tool: Tool<any>;
let logger: CrashLogger;
Expand All @@ -12,6 +15,8 @@ describe('CrashLogger', () => {
const oldWrite = fs.writeFileSync.bind(fs);

beforeEach(() => {
(execa.shellSync as jest.Mock).mockReturnValue({ stdout: '' });

tool = mockTool();
logger = new CrashLogger(tool);
spy = jest.fn();
Expand Down
2 changes: 0 additions & 2 deletions packages/core/tests/Reporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,9 @@ describe('Reporter', () => {

beforeEach(() => {
process.env.CI = '';
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
process.env.CI = oldCI;
});

Expand Down
54 changes: 37 additions & 17 deletions packages/core/tests/Routine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Task from '../src/Task';
import Tool from '../src/Tool';
import { STATUS_PASSED, STATUS_FAILED, STATUS_RUNNING } from '../src/constants';

jest.mock('execa');

describe('Routine', () => {
let routine: Routine<any, any>;
let tool: Tool<any, any>;
Expand Down Expand Up @@ -164,32 +166,50 @@ describe('Routine', () => {
});

describe('executeCommand()', () => {
class FakeStream {
pipe() {
return this;
}

on(event: string, handler: (line: string) => any) {
handler('Mocked stream line');

return this;
}

toString() {
return '';
}
}

beforeEach(() => {
((execa as any) as jest.Mock).mockImplementation((cmd, args) => ({
cmd: `${cmd} ${args.join(' ')}`,
stdout: new FakeStream(),
stderr: new FakeStream(),
}));

(execa.shell as jest.Mock).mockImplementation(cmd => ({ cmd: `/bin/sh -c ${cmd}` }));
});

it('runs a local command', async () => {
const result = await routine.executeCommand('yarn', ['-v']);

expect(result).toEqual(
expect.objectContaining({ cmd: 'yarn -v', stdout: expect.stringMatching(/[\d.]+/u) }),
);
expect(result).toEqual(expect.objectContaining({ cmd: 'yarn -v' }));
});

it('runs a local command in a shell', async () => {
const spy = jest.spyOn(execa, 'shell');
const result = await routine.executeCommand('echo', ['boost'], { shell: true });

expect(spy).toHaveBeenCalledWith('echo boost', {});
expect(result).toEqual(
expect.objectContaining({ cmd: '/bin/sh -c echo boost', stdout: 'boost' }),
);
expect(execa.shell).toHaveBeenCalledWith('echo boost', {});
expect(result).toEqual({ cmd: '/bin/sh -c echo boost' });
});

it('runs a local command in a shell with args used directly', async () => {
const spy = jest.spyOn(execa, 'shell');
const result = await routine.executeCommand('echo boost', [], { shell: true });

expect(spy).toHaveBeenCalledWith('echo boost', {});
expect(result).toEqual(
expect.objectContaining({ cmd: '/bin/sh -c echo boost', stdout: 'boost' }),
);
expect(execa.shell).toHaveBeenCalledWith('echo boost', {});
expect(result).toEqual({ cmd: '/bin/sh -c echo boost' });
});

it('calls callback with stream', async () => {
Expand All @@ -210,12 +230,12 @@ describe('Routine', () => {
await routine.executeCommand('yarn', ['-v'], { task });

expect(spy1).toHaveBeenCalledWith('command', ['yarn']);
expect(spy1).toHaveBeenCalledWith('command.data', ['yarn', expect.stringMatching(/[\d.]+/u)]);
expect(spy1).toHaveBeenCalledWith('command.data', ['yarn', expect.anything()]);

expect(spy2).toHaveBeenCalledWith('command', ['yarn', expect.anything()]);
expect(spy2).toHaveBeenCalledWith('command.data', [
'yarn',
expect.stringMatching(/[\d.]+/u),
expect.anything(),
expect.anything(),
]);
});
Expand All @@ -227,7 +247,7 @@ describe('Routine', () => {

await routine.executeCommand('yarn', ['--help'], { task });

expect(task.statusText).toEqual(expect.stringContaining('learn more about Yarn'));
expect(task.statusText).toBe('Mocked stream line');
});

it('sets `output` on task', async () => {
Expand All @@ -237,7 +257,7 @@ describe('Routine', () => {

await routine.executeCommand('yarn', ['-v'], { task });

expect(task.output).toMatch(/\d+\.\d+\.\d+/u);
expect(task.output).toBe('Mocked stream lineMocked stream line');
});

it('doesnt set `statusText` or `output` on task when not running', async () => {
Expand Down
14 changes: 14 additions & 0 deletions packages/core/tests/executors/Pool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ describe('PoolExecutor', () => {
});
});

afterEach(() => {
// Resolve any pending promises
if (executor.resolver) {
executor.resolver({
results: [],
errors: [],
});
}
});

it('triggers tasks in parallel', async () => {
const foo = new Task('foo', () => 123);
const bar = new Task('bar', () => {
Expand Down Expand Up @@ -54,6 +64,8 @@ describe('PoolExecutor', () => {
});

it('maxes at concurrency limit', async () => {
jest.useRealTimers();

executor.options.concurrency = 1;
executor.nextItem = () => {}; // Stop it exhausting

Expand All @@ -65,6 +77,8 @@ describe('PoolExecutor', () => {

expect(executor.queue).toHaveLength(2);
expect(executor.running).toHaveLength(0);

jest.useFakeTimers();
});

it('cycles 1 by 1', async () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/tests/reporters/BoostReporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
STATUS_PASSED,
} from '../../src/constants';

const oldNow = Date.now;
const oldDateNow = Date.now;

describe('BoostReporter', () => {
let reporter: BoostReporter;
Expand Down Expand Up @@ -49,7 +49,7 @@ describe('BoostReporter', () => {
});

afterEach(() => {
Date.now = oldNow;
Date.now = oldDateNow;
});

describe('bootstrap()', () => {
Expand Down