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

Add Global Setup/Teardown APIs #4716

Merged
merged 1 commit into from
Dec 13, 2017
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@

### Features

* `[jest-config]` Add Global Setup/Teardown options
([#4716](https://github.com/facebook/jest/pull/4716))
* `[jest-config]` Add `testEnvironmentOptions` to apply to jsdom options or node
context. ([#5003](https://github.com/facebook/jest/pull/5003))
* `[jest-jasmine2]` Update Timeout error message to `jest.timeout` and display
Expand Down
10 changes: 10 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@ Note that, if you specify a global reference value (like an object or array)
here, and some code mutates that value in the midst of running a test, that
mutation will _not_ be persisted across test runs for other test files.

### `globalSetup` [string]
Default: `undefined`

This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites.

### `globalTeardown` [string]
Default: `undefined`

This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites.

### `mapCoverage` [boolean]

##### available in Jest **20.0.0+**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ exports[`--showConfig outputs config info and exits 1`] = `
],
\\"detectLeaks\\": false,
\\"expand\\": false,
\\"globalSetup\\": null,
\\"globalTeardown\\": null,
\\"listTests\\": false,
\\"mapCoverage\\": false,
\\"maxWorkers\\": \\"[maxWorkers]\\",
Expand Down
29 changes: 29 additions & 0 deletions integration_tests/__tests__/global_setup.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @flow
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');
const runJest = require('../runJest');
const {cleanup} = require('../utils');

const DIR = path.join(os.tmpdir(), 'jest_global_setup');

beforeEach(() => cleanup(DIR));
afterAll(() => cleanup(DIR));

test('globalSetup is triggered once before all test suites', () => {
const setupPath = path.resolve(__dirname, '../global_setup/setup.js');
const result = runJest.json('global_setup', [`--globalSetup=${setupPath}`]);
expect(result.status).toBe(0);
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(1);
const setup = fs.readFileSync(path.join(DIR, files[0]), 'utf8');
expect(setup).toBe('setup');
});
36 changes: 36 additions & 0 deletions integration_tests/__tests__/global_teardown.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* @flow
*/
'use strict';

const fs = require('fs');
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');
const runJest = require('../runJest');
const {cleanup} = require('../utils');

const DIR = path.join(os.tmpdir(), 'jest_global_teardown');

beforeEach(() => cleanup(DIR));
afterAll(() => cleanup(DIR));

test('globalTeardown is triggered once after all test suites', () => {
mkdirp.sync(DIR);
const teardownPath = path.resolve(
__dirname,
'../global_teardown/teardown.js',
);
const result = runJest.json('global_teardown', [
`--globalTeardown=${teardownPath}`,
]);
expect(result.status).toBe(0);
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(1);
const teardown = fs.readFileSync(path.join(DIR, files[0]), 'utf8');
expect(teardown).toBe('teardown');
});
20 changes: 20 additions & 0 deletions integration_tests/global_setup/__tests__/setup1.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_setup');

test('should exist setup file', () => {
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(1);
const setup = fs.readFileSync(path.join(DIR, files[0]), 'utf8');
expect(setup).toBe('setup');
});
20 changes: 20 additions & 0 deletions integration_tests/global_setup/__tests__/setup2.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_setup');

test('should exist setup file', () => {
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(1);
const setup = fs.readFileSync(path.join(DIR, files[0]), 'utf8');
expect(setup).toBe('setup');
});
20 changes: 20 additions & 0 deletions integration_tests/global_setup/__tests__/setup3.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_setup');

test('should exist setup file', () => {
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(1);
const setup = fs.readFileSync(path.join(DIR, files[0]), 'utf8');
expect(setup).toBe('setup');
});
5 changes: 5 additions & 0 deletions integration_tests/global_setup/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "node"
}
}
22 changes: 22 additions & 0 deletions integration_tests/global_setup/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const crypto = require('crypto');
const fs = require('fs');
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_setup');

module.exports = function() {
return new Promise((resolve, reject) => {
mkdirp.sync(DIR);
const fileId = crypto.randomBytes(20).toString('hex');
fs.writeFileSync(path.join(DIR, fileId), 'setup');
resolve();
});
};
18 changes: 18 additions & 0 deletions integration_tests/global_teardown/__tests__/teardown1.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_teardown');

test('should not exist teardown file', () => {
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(0);
});
18 changes: 18 additions & 0 deletions integration_tests/global_teardown/__tests__/teardown2.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_teardown');

test('should not exist teardown file', () => {
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(0);
});
18 changes: 18 additions & 0 deletions integration_tests/global_teardown/__tests__/teardown3.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_teardown');

test('should not exist teardown file', () => {
const files = fs.readdirSync(DIR);
expect(files).toHaveLength(0);
});
5 changes: 5 additions & 0 deletions integration_tests/global_teardown/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "node"
}
}
22 changes: 22 additions & 0 deletions integration_tests/global_teardown/teardown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const crypto = require('crypto');
const fs = require('fs');
const mkdirp = require('mkdirp');
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_global_teardown');

module.exports = function() {
return new Promise((resolve, reject) => {
mkdirp.sync(DIR);
const fileId = crypto.randomBytes(20).toString('hex');
fs.writeFileSync(path.join(DIR, fileId), 'teardown');
resolve();
});
};
8 changes: 8 additions & 0 deletions packages/jest-cli/src/cli/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,14 @@ export const options = {
'adequately cleaned up.',
type: 'boolean',
},
globalSetup: {
description: 'The path to a module that runs before All Tests.',
type: 'string',
},
globalTeardown: {
description: 'The path to a module that runs after All Tests.',
type: 'string',
},
globals: {
description:
'A JSON string with map of global variables that need ' +
Expand Down
8 changes: 8 additions & 0 deletions packages/jest-cli/src/run_jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ export default (async function runJest({
changedFilesPromise: ?ChangedFilesPromise,
onComplete: (testResults: AggregatedResult) => any,
}) {
if (globalConfig.globalSetup) {
// $FlowFixMe
await require(globalConfig.globalSetup)();
}
const sequencer = new TestSequencer();
let allTests = [];

Expand Down Expand Up @@ -172,6 +176,10 @@ export default (async function runJest({

sequencer.cacheResults(allTests, results);

if (globalConfig.globalTeardown) {
// $FlowFixMe
await require(globalConfig.globalTeardown)();
}
return processResults(results, {
isJSON: globalConfig.json,
onComplete,
Expand Down
2 changes: 2 additions & 0 deletions packages/jest-config/src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export default ({
coverageReporters: ['json', 'text', 'lcov', 'clover'],
detectLeaks: false,
expand: false,
globalSetup: null,
globalTeardown: null,
globals: {},
haste: {
providesModuleNodeModules: [],
Expand Down
2 changes: 2 additions & 0 deletions packages/jest-config/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ const getConfigs = (
expand: options.expand,
findRelatedTests: options.findRelatedTests,
forceExit: options.forceExit,
globalSetup: options.globalSetup,
globalTeardown: options.globalTeardown,
json: options.json,
lastCommit: options.lastCommit,
listTests: options.listTests,
Expand Down
2 changes: 2 additions & 0 deletions packages/jest-config/src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,8 @@ export default function normalize(options: InitialOptions, argv: Argv) {
case 'detectLeaks':
case 'displayName':
case 'expand':
case 'globalSetup':
case 'globalTeardown':
case 'globals':
case 'findRelatedTests':
case 'forceExit':
Expand Down
2 changes: 2 additions & 0 deletions test_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ const DEFAULT_GLOBAL_CONFIG: GlobalConfig = {
expand: false,
findRelatedTests: false,
forceExit: false,
globalSetup: null,
globalTeardown: null,
json: false,
lastCommit: false,
listTests: false,
Expand Down
2 changes: 2 additions & 0 deletions types/Argv.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export type Argv = {|
expand: boolean,
findRelatedTests: boolean,
forceExit: boolean,
globalSetup: ?string,
globalTeardown: ?string,
globals: string,
h: boolean,
haste: string,
Expand Down
6 changes: 6 additions & 0 deletions types/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export type DefaultOptions = {|
coverageReporters: Array<string>,
expand: boolean,
globals: ConfigGlobals,
globalSetup: ?string,
globalTeardown: ?string,
haste: HasteConfig,
detectLeaks: boolean,
mapCoverage: boolean,
Expand Down Expand Up @@ -87,6 +89,8 @@ export type InitialOptions = {
forceExit?: boolean,
json?: boolean,
globals?: ConfigGlobals,
globalSetup?: ?string,
globalTeardown?: ?string,
haste?: HasteConfig,
reporters?: Array<ReporterConfig | string>,
logHeapUsage?: boolean,
Expand Down Expand Up @@ -163,6 +167,8 @@ export type GlobalConfig = {|
findRelatedTests: boolean,
forceExit: boolean,
json: boolean,
globalSetup: ?string,
globalTeardown: ?string,
lastCommit: boolean,
logHeapUsage: boolean,
listTests: boolean,
Expand Down