Skip to content

Commit

Permalink
Allow setting a test environment per file
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Feb 22, 2017
1 parent 3002e05 commit 84e6c9d
Show file tree
Hide file tree
Showing 6 changed files with 133 additions and 56 deletions.
13 changes: 12 additions & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,18 @@ To make a dependency explicit instead of implicit, you can call [`expect.addSnap
### `testEnvironment` [string]
Default: `"jsdom"`

The test environment that will be used for testing. The default environment in Jest is a browser-like environment through [jsdom](https://github.com/tmpvar/jsdom). If you are building a node service, you can use the `node` option to use a node-like environment instead. Combining the test environments is currently not possible but the `jsdom` environment can be seen as a superset of the `node` one.
The test environment that will be used for testing. The default environment in Jest is a browser-like environment through [jsdom](https://github.com/tmpvar/jsdom). If you are building a node service, you can use the `node` option to use a node-like environment instead. If some tests require another environment, you can add a `@testEnvironment` pragma.

```js
/**
* @testEnvironment jsdom
*/

test('use document in a mostly node environment', () => {
const ele = document.createElement('div');
expect(ele).not.toBeNull();
});
```

You can create your own module that will be used for setting up the test environment. The module must export a class with `runScript` and `dispose` methods. See the [node](https://github.com/facebook/jest/blob/master/packages/jest-environment-node/src/index.js) or [jsdom](https://github.com/facebook/jest/blob/master/packages/jest-environment-jsdom/src/index.js) environments as examples.

Expand Down
23 changes: 23 additions & 0 deletions integration_tests/__tests__/test-environment-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/
'use strict';

const runJest = require('../runJest');

const testFixturePackage = require('../test-environment/package.json');

it('respects testEnvironment pragma', () => {
expect(testFixturePackage.jest.testEnvironment).toEqual('node');

const result = runJest.json('test-environment').json;

expect(result.success).toBe(true);
expect(result.numTotalTests).toBe(1);
});
19 changes: 19 additions & 0 deletions integration_tests/test-environment/__tests__/env-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/* eslint-env browser */

/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';

/**
* @testEnvironment jsdom
*/

test('stub', () => {
const ele = document.createElement('div');
expect(ele).not.toBeNull();
});
5 changes: 5 additions & 0 deletions integration_tests/test-environment/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "node"
}
}
127 changes: 72 additions & 55 deletions packages/jest-cli/src/runTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,74 +13,91 @@ import type {Path, Config} from 'types/Config';
import type {TestResult} from 'types/TestResult';
import type {Resolver} from 'types/Resolve';

const fs = require('fs');
const {getTestEnvironment} = require('jest-config');
const BufferedConsole = require('./lib/BufferedConsole');
const promisify = require('./lib/promisify');
const {
Console,
NullConsole,
setGlobal,
} = require('jest-util');
const getConsoleOutput = require('./reporters/getConsoleOutput');

const testEnvironmentPragmaRegex = /@testEnvironment\s+(.*)/;

function runTest(path: Path, config: Config, resolver: Resolver) {
/* $FlowFixMe */
const TestEnvironment = require(config.testEnvironment);
/* $FlowFixMe */
const TestRunner = require(config.testRunner);
/* $FlowFixMe */
const ModuleLoader = require(config.moduleLoader || 'jest-runtime');
return promisify(fs.readFile)(path, 'utf8').then(data => {
let testEnvironment = config.testEnvironment;

const testEnvironmentPragma = data.match(testEnvironmentPragmaRegex);

const env = new TestEnvironment(config);
const TestConsole =
config.verbose
? Console
: (config.silent
? NullConsole
: BufferedConsole
if (testEnvironmentPragma && testEnvironmentPragma.length > 1) {
testEnvironment = getTestEnvironment(
Object.assign({}, config, {testEnvironment: testEnvironmentPragma[1]})
);
const testConsole = new TestConsole(
config.useStderr ? process.stderr : process.stdout,
process.stderr,
(type, message) => getConsoleOutput(
config.rootDir,
!!config.verbose,
// 4 = the console call is burried 4 stack frames deep
BufferedConsole.write([], type, message, 4),
),
);
setGlobal(env.global, 'console', testConsole);
const runtime = new ModuleLoader(config, env, resolver);
const start = Date.now();
return TestRunner(config, env, runtime, path)
.then((result: TestResult) => {
const testCount =
result.numPassingTests +
result.numFailingTests +
result.numPendingTests;
result.perfStats = {end: Date.now(), start};
result.testFilePath = path;
result.coverage = runtime.getAllCoverageInfo();
result.console = testConsole.getBuffer();
result.skipped = testCount === result.numPendingTests;
return result;
})
.then(
result => Promise.resolve().then(() => {
env.dispose();
if (config.logHeapUsage) {
if (global.gc) {
global.gc();
}
result.memoryUsage = process.memoryUsage().heapUsed;
}
}

/* $FlowFixMe */
const TestEnvironment = require(testEnvironment);
/* $FlowFixMe */
const TestRunner = require(config.testRunner);
/* $FlowFixMe */
const ModuleLoader = require(config.moduleLoader || 'jest-runtime');

// Delay the resolution to allow log messages to be output.
return new Promise(resolve => setImmediate(() => resolve(result)));
}),
err => Promise.resolve().then(() => {
env.dispose();
throw err;
}),
const env = new TestEnvironment(config);
const TestConsole =
config.verbose
? Console
: (config.silent
? NullConsole
: BufferedConsole
);
const testConsole = new TestConsole(
config.useStderr ? process.stderr : process.stdout,
process.stderr,
(type, message) => getConsoleOutput(
config.rootDir,
!!config.verbose,
// 4 = the console call is buried 4 stack frames deep
BufferedConsole.write([], type, message, 4),
),
);
setGlobal(env.global, 'console', testConsole);
const runtime = new ModuleLoader(config, env, resolver);
const start = Date.now();
return TestRunner(config, env, runtime, path)
.then((result: TestResult) => {
const testCount =
result.numPassingTests +
result.numFailingTests +
result.numPendingTests;
result.perfStats = {end: Date.now(), start};
result.testFilePath = path;
result.coverage = runtime.getAllCoverageInfo();
result.console = testConsole.getBuffer();
result.skipped = testCount === result.numPendingTests;
return result;
})
.then(
result => Promise.resolve().then(() => {
env.dispose();
if (config.logHeapUsage) {
if (global.gc) {
global.gc();
}
result.memoryUsage = process.memoryUsage().heapUsed;
}

// Delay the resolution to allow log messages to be output.
return new Promise(resolve => setImmediate(() => resolve(result)));
}),
err => Promise.resolve().then(() => {
env.dispose();
throw err;
}),
);
});
}

module.exports = runTest;
2 changes: 2 additions & 0 deletions packages/jest-config/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const loadFromFile = require('./loadFromFile');
const loadFromPackage = require('./loadFromPackage');
const normalize = require('./normalize');
const setFromArgv = require('./setFromArgv');
const {getTestEnvironment} = require('./utils');

const readConfig = (argv: Object, packageRoot: string) =>
readRawConfig(argv, packageRoot)
Expand Down Expand Up @@ -60,6 +61,7 @@ const readRawConfig = (argv, root) => {
};

module.exports = {
getTestEnvironment,
normalize,
readConfig,
};

0 comments on commit 84e6c9d

Please sign in to comment.