Skip to content

Commit

Permalink
Add Global Setup/Teardown APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
xfumihiro committed Oct 20, 2017
1 parent f162044 commit 2253417
Show file tree
Hide file tree
Showing 23 changed files with 270 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* `[jest-message-util]` Always remove node internals from stacktraces ([#4695](https://github.com/facebook/jest/pull/4695))

### Features
* `[jest-config]` Add Global Setup/Teardown options ([#4716](https://github.com/facebook/jest/pull/4716))
* `[jest-environment-*]` [**BREAKING**] Add Async Test Environment APIs, dispose is now teardown ([#4506](https://github.com/facebook/jest/pull/4506))
* `[jest-cli]` Add an option to clear the cache ([#4430](https://github.com/facebook/jest/pull/4430))
* `[babel-plugin-jest-hoist]` Improve error message, that the second argument of `jest.mock` must be an inline function ([#4593](https://github.com/facebook/jest/pull/4593))
Expand Down
10 changes: 10 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,16 @@ For example, the following would create a global `__DEV__` variable set to `true

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 @@ -66,6 +66,8 @@ exports[`--showConfig outputs config info and exits 1`] = `
\\"clover\\"
],
\\"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 runJest = require('../runJest');
const {cleanup} = require('../utils');

const DIR = os.tmpdir() + '/jest';

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

test('globalSetup is triggered once before all test suites', () => {
const path = require('path');
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.length).toBe(1);
const setup = fs.readFileSync(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 os = require('os');
const runJest = require('../runJest');
const {cleanup} = require('../utils');
const mkdirp = require('mkdirp');

const DIR = os.tmpdir() + '/jest';

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

test('globalTeardown is triggered once after all test suites', () => {
mkdirp.sync(DIR);
const path = require('path');
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.length).toBe(1);
const teardown = fs.readFileSync(DIR + '/' + files[0], 'utf8');
expect(teardown).toBe('teardown');
});
19 changes: 19 additions & 0 deletions integration_tests/global_setup/__tests__/setup1.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* 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 DIR = os.tmpdir() + '/jest';

test('should exist setup file', () => {
const files = fs.readdirSync(DIR);
expect(files.length).toBe(1);
const setup = fs.readFileSync(DIR + '/' + files[0], 'utf8');
expect(setup).toBe('setup');
});
19 changes: 19 additions & 0 deletions integration_tests/global_setup/__tests__/setup2.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* 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 DIR = os.tmpdir() + '/jest';

test('should exist setup file', () => {
const files = fs.readdirSync(DIR);
expect(files.length).toBe(1);
const setup = fs.readFileSync(DIR + '/' + files[0], 'utf8');
expect(setup).toBe('setup');
});
19 changes: 19 additions & 0 deletions integration_tests/global_setup/__tests__/setup3.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* 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 DIR = os.tmpdir() + '/jest';

test('should exist setup file', () => {
const files = fs.readdirSync(DIR);
expect(files.length).toBe(1);
const setup = fs.readFileSync(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"
}
}
21 changes: 21 additions & 0 deletions integration_tests/global_setup/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* 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 fs = require('fs');
const crypto = require('crypto');
const os = require('os');
const mkdirp = require('mkdirp');

const DIR = os.tmpdir() + '/jest';

module.exports = function() {
return new Promise((resolve, reject) => {
mkdirp.sync(DIR);
const fileId = crypto.randomBytes(20).toString('hex');
fs.writeFileSync(DIR + '/' + fileId, 'setup');
resolve();
});
};
17 changes: 17 additions & 0 deletions integration_tests/global_teardown/__tests__/teardown1.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* 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 DIR = os.tmpdir() + '/jest';

test('should not exist teardown file', () => {
const files = fs.readdirSync(DIR);
expect(files.length).toBe(0);
});
17 changes: 17 additions & 0 deletions integration_tests/global_teardown/__tests__/teardown2.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* 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 DIR = os.tmpdir() + '/jest';

test('should not exist teardown file', () => {
const files = fs.readdirSync(DIR);
expect(files.length).toBe(0);
});
17 changes: 17 additions & 0 deletions integration_tests/global_teardown/__tests__/teardown3.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* 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 DIR = os.tmpdir() + '/jest';

test('should not exist teardown file', () => {
const files = fs.readdirSync(DIR);
expect(files.length).toBe(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"
}
}
21 changes: 21 additions & 0 deletions integration_tests/global_teardown/teardown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* 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 fs = require('fs');
const crypto = require('crypto');
const os = require('os');
const mkdirp = require('mkdirp');

const DIR = os.tmpdir() + '/jest';

module.exports = function() {
return new Promise((resolve, reject) => {
mkdirp.sync(DIR);
const fileId = crypto.randomBytes(20).toString('hex');
fs.writeFileSync(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 @@ -231,6 +231,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 @@ -94,6 +94,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 = [];
const testRunData = await Promise.all(
Expand Down Expand Up @@ -161,6 +165,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 @@ -37,6 +37,8 @@ export default ({
coveragePathIgnorePatterns: [NODE_MODULES_REGEXP],
coverageReporters: ['json', 'text', 'lcov', 'clover'],
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 @@ -84,6 +84,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 @@ -452,6 +452,8 @@ export default function normalize(options: InitialOptions, argv: Argv) {
case 'coverageThreshold':
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 @@ -23,6 +23,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,
mapCoverage: boolean,
moduleDirectories: Array<string>,
Expand Down Expand Up @@ -83,6 +85,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 @@ -155,6 +159,8 @@ export type GlobalConfig = {|
findRelatedTests: boolean,
forceExit: boolean,
json: boolean,
globalSetup: ?string,
globalTeardown: ?string,
lastCommit: boolean,
logHeapUsage: boolean,
listTests: boolean,
Expand Down

0 comments on commit 2253417

Please sign in to comment.