Skip to content

Commit

Permalink
docs: prefer jest.require* instead of require.require* (jestjs#7210)
Browse files Browse the repository at this point in the history
  • Loading branch information
thymikee authored and SimenB committed Oct 20, 2018
1 parent 9df985c commit 4ec517e
Show file tree
Hide file tree
Showing 53 changed files with 144 additions and 101 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
- `[docs]` Removed useless expect.assertions in `TestingAsyncCode.md` ([#7131](https://github.com/facebook/jest/pull/7131))
- `[docs]` Remove references to `@providesModule` which isn't supported anymore ([#7147](https://github.com/facebook/jest/pull/7147))
- `[docs]` Update `setupFiles` documentation for clarity ([#7187](https://github.com/facebook/jest/pull/7187))
- `[docs]` Change `require.require*` to `jest.require*` ([#7210](https://github.com/facebook/jest/pull/7210))
- `[jest-circus]` Add readme.md ([#7198](https://github.com/facebook/jest/pull/7198))

### Performance
Expand Down
8 changes: 0 additions & 8 deletions docs/GlobalAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,14 +434,6 @@ test('will be ran', () => {
});
```

### `require.requireActual(moduleName)`

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

### `require.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

### `test(name, fn, timeout)`

Also under the alias: `it(name, fn, timeout)`
Expand Down
10 changes: 10 additions & 0 deletions docs/JestObjectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ The `jest` object is automatically in scope within every test file. The methods
- [`jest.runAllTimers()`](#jestrunalltimers)
- [`jest.advanceTimersByTime(msToRun)`](#jestadvancetimersbytimemstorun)
- [`jest.runOnlyPendingTimers()`](#jestrunonlypendingtimers)
- [`jest.requireActual()`](#jestrequireactual)
- [`jest.requireMock()`](#jestrequiremock)
- [`jest.setMock(moduleName, moduleExports)`](#jestsetmockmodulename-moduleexports)
- [`jest.setTimeout(timeout)`](#jestsettimeouttimeout)
- [`jest.useFakeTimers()`](#jestusefaketimers)
Expand Down Expand Up @@ -362,6 +364,14 @@ Executes only the macro-tasks that are currently pending (i.e., only the tasks t

This is useful for scenarios such as one where the module being tested schedules a `setTimeout()` whose callback schedules another `setTimeout()` recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time.

### `jest.requireActual(moduleName)`

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

### `jest.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

### `jest.setMock(moduleName, moduleExports)`

Explicitly supplies the mock object that the module system should return for the specified module.
Expand Down
2 changes: 1 addition & 1 deletion docs/ManualMocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ describe('listFilesInDirectorySync', () => {

The example mock shown here uses [`jest.genMockFromModule`](JestObjectAPI.md#jestgenmockfrommodulemodulename) to generate an automatic mock, and overrides its default behavior. This is the recommended approach, but is completely optional. If you do not want to use the automatic mock at all, you can simply export your own functions from the mock file. One downside to fully manual mocks is that they're manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it's best to use or extend the automatic mock when it works for your needs.

To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using `require.requireActual(moduleName)` in your manual mock and amending it with mock functions before exporting it.
To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using `jest.requireActual(moduleName)` in your manual mock and amending it with mock functions before exporting it.

The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/master/examples/manual-mocks).

Expand Down
2 changes: 1 addition & 1 deletion docs/Troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ If a promise doesn't resolve at all, this error might be thrown:
- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.`
```

Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = require.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.
Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = jest.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.

If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout`

Expand Down
2 changes: 1 addition & 1 deletion docs/TutorialReactNative.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ Or if you'd like to create your own manual mock, you can do something like this:

```js
jest.mock('Text', () => {
const RealComponent = require.requireActual('Text');
const RealComponent = jest.requireActual('Text');
const React = require('React');
class Text extends React.Component {
render() {
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/jest_require_actual.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ const DIR = path.resolve(os.tmpdir(), 'jest_require_actual_test');
beforeEach(() => cleanup(DIR));
afterAll(() => cleanup(DIR));

test('understands dependencies using require.requireActual', () => {
test('understands dependencies using jest.requireActual', () => {
writeFiles(DIR, {
'.watchmanconfig': '',
'__tests__/a.test.js': `
const a = require.requireActual('../a');
const a = jest.requireActual('../a');
test('a', () => {});
`,
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/jest_require_mock.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ const DIR = path.resolve(os.tmpdir(), 'jest_require_mock_test');
beforeEach(() => cleanup(DIR));
afterAll(() => cleanup(DIR));

test('understands dependencies using require.requireMock', () => {
test('understands dependencies using jest.requireMock', () => {
writeFiles(DIR, {
'.watchmanconfig': '',
'__tests__/a.test.js': `
const a = require.requireMock('../a');
const a = jest.requireMock('../a');
test('a', () => {});
`,
Expand Down
2 changes: 1 addition & 1 deletion examples/module-mock/__tests__/partial_mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import defaultExport, {apple, strawberry} from '../fruit';

jest.mock('../fruit', () => {
const originalModule = require.requireActual('../fruit');
const originalModule = jest.requireActual('../fruit');
const mockedModule = jest.genMockFromModule('../fruit');

//Mock the default export and named export 'apple'.
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/src/__tests__/fake_chalk.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
'use strict';

const fakeChalk = require.requireActual('../fake_chalk');
const fakeChalk = jest.requireActual('../fake_chalk');

describe('Fake Chalk', () => {
it('returns input when invoked', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const {makeGlobalConfig, makeProjectConfig} = require('../../../../TestUtils');

jest.mock('jest-runtime', () => {
// $FlowFixMe requireActual
const realRuntime = require.requireActual('jest-runtime');
const realRuntime = jest.requireActual('jest-runtime');
realRuntime.shouldInstrument = () => true;
return realRuntime;
});
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-config/src/__tests__/normalize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import normalize from '../normalize';

jest.mock('jest-resolve');

jest.mock('path', () => require.requireActual('path').posix);
jest.mock('path', () => jest.requireActual('path').posix);

const crypto = require('crypto');
const path = require('path');
Expand Down Expand Up @@ -1009,7 +1009,7 @@ describe('preset', () => {

test('throws when preset is invalid', () => {
jest.doMock('/node_modules/react-native/jest-preset.json', () =>
require.requireActual('./jest-preset.json'),
jest.requireActual('./jest-preset.json'),
);

expect(() => {
Expand Down Expand Up @@ -1263,7 +1263,7 @@ describe('testPathPattern', () => {

describe('win32', () => {
beforeEach(() => {
jest.mock('path', () => require.requireActual('path').win32);
jest.mock('path', () => jest.requireActual('path').win32);
require('jest-resolve').findNodeModule = findNodeModule;
});

Expand Down
2 changes: 1 addition & 1 deletion packages/jest-editor-support/src/__tests__/runner.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jest.mock('child_process', () => ({spawn: jest.fn()}));
jest.mock('os', () => ({tmpdir: jest.fn()}));
jest.mock('fs', () => {
// $FlowFixMe requireActual
const readFileSync = require.requireActual('fs').readFileSync;
const readFileSync = jest.requireActual('fs').readFileSync;

// Replace `readFile` with `readFileSync` so we don't get multiple threads
return {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-environment-jsdom/src/__mocks__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
'use strict';

const vm = require.requireActual('vm');
const vm = jest.requireActual('vm');

const JSDOMEnvironment = jest.genMockFromModule('../index');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
'use strict';

const JSDomEnvironment = require.requireActual('../');
const JSDomEnvironment = jest.requireActual('../');

describe('JSDomEnvironment', () => {
it('should configure setTimeout/setInterval to use the browser api', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
'use strict';

const NodeEnvironment = require.requireActual('../');
const NodeEnvironment = jest.requireActual('../');

describe('NodeEnvironment', () => {
it('uses a copy of the process object', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
describe('normalizePathSep', () => {
it('does nothing on posix', () => {
jest.resetModules();
jest.mock('path', () => require.requireActual('path').posix);
jest.mock('path', () => jest.requireActual('path').posix);
const normalizePathSep = require('../normalize_path_sep').default;
expect(normalizePathSep('foo/bar/baz.js')).toEqual('foo/bar/baz.js');
});

it('replace slashes on windows', () => {
jest.resetModules();
jest.mock('path', () => require.requireActual('path').win32);
jest.mock('path', () => jest.requireActual('path').win32);
const normalizePathSep = require('../normalize_path_sep').default;
expect(normalizePathSep('foo/bar/baz.js')).toEqual('foo\\bar\\baz.js');
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ jest
.mock('fs', () =>
// Node 10.5.x compatibility
Object.assign({}, jest.genMockFromModule('fs'), {
ReadStream: require.requireActual('fs').ReadStream,
WriteStream: require.requireActual('fs').WriteStream,
ReadStream: jest.requireActual('fs').ReadStream,
WriteStream: jest.requireActual('fs').WriteStream,
}),
)
.mock('graceful-fs')
.mock('jest-haste-map', () => ({
getCacheFilePath: (cacheDir, baseDir, version) => cacheDir + baseDir,
}))
.mock('jest-util', () => {
const util = require.requireActual('jest-util');
const util = jest.requireActual('jest-util');
util.createDirectory = jest.fn();
return util;
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ let OnlyRequiredFromMock;
let moduleStateValue = 'default';

try {
OnlyRequiredFromMock = require.requireActual('OnlyRequiredFromMock');
OnlyRequiredFromMock = jest.requireActual('OnlyRequiredFromMock');
} catch (e) {
// If the module cannot be loaded, use a dummy value. There is one test
// that specifically tests for the correct value which ensures this feature
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-snapshot/src/__mocks__/prettier.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const prettier = require.requireActual('prettier');
const prettier = jest.requireActual('prettier');

module.exports = {
format: (text, opts) =>
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-util/src/__tests__/get_callsite.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import getCallsite from '../get_callsite';
// Node 10.5.x compatibility
jest.mock('fs', () =>
Object.assign({}, jest.genMockFromModule('fs'), {
ReadStream: require.requireActual('fs').ReadStream,
WriteStream: require.requireActual('fs').WriteStream,
ReadStream: jest.requireActual('fs').ReadStream,
WriteStream: jest.requireActual('fs').WriteStream,
}),
);

Expand Down
10 changes: 0 additions & 10 deletions website/versioned_docs/version-22.0/GlobalAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,6 @@ describe.skip('my other beverage', () => {
});
```

Using `describe.skip` is often just an easier alternative to temporarily commenting out a chunk of tests.

### `require.requireActual(moduleName)`

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

### `require.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

### `test(name, fn, timeout)`

Also under the alias: `it(name, fn, timeout)`
Expand Down
10 changes: 10 additions & 0 deletions website/versioned_docs/version-22.0/JestObjectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ The `jest` object is automatically in scope within every test file. The methods
- [`jest.runAllTimers()`](#jestrunalltimers)
- [`jest.advanceTimersByTime(msToRun)`](#jestadvancetimersbytimemstorun)
- [`jest.runOnlyPendingTimers()`](#jestrunonlypendingtimers)
- [`jest.requireActual()`](#jestrequireactual)
- [`jest.requireMock()`](#jestrequiremock)
- [`jest.setMock(moduleName, moduleExports)`](#jestsetmockmodulename-moduleexports)
- [`jest.setTimeout(timeout)`](#jestsettimeouttimeout)
- [`jest.useFakeTimers()`](#jestusefaketimers)
Expand Down Expand Up @@ -266,6 +268,14 @@ Executes only the macro-tasks that are currently pending (i.e., only the tasks t

This is useful for scenarios such as one where the module being tested schedules a `setTimeout()` whose callback schedules another `setTimeout()` recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time.

### `jest.requireActual(moduleName)`

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

### `jest.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

### `jest.setMock(moduleName, moduleExports)`

Explicitly supplies the mock object that the module system should return for the specified module.
Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-22.0/ManualMocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ describe('listFilesInDirectorySync', () => {

The example mock shown here uses [`jest.genMockFromModule`](JestObjectAPI.md#jestgenmockfrommodulemodulename) to generate an automatic mock, and overrides its default behavior. This is the recommended approach, but is completely optional. If you do not want to use the automatic mock at all, you can simply export your own functions from the mock file. One downside to fully manual mocks is that they're manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it's best to use or extend the automatic mock when it works for your needs.

To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using `require.requireActual(moduleName)` in your manual mock and amending it with mock functions before exporting it.
To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using `jest.requireActual(moduleName)` in your manual mock and amending it with mock functions before exporting it.

The code for this example is available at [examples/manual_mocks](https://github.com/facebook/jest/tree/master/examples/manual_mocks).

Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-22.0/Troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ If a promise doesn't resolve at all, this error might be thrown:
- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.`
```

Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = require.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.
Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = jest.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.

If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout`

Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-22.0/TutorialReactNative.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ Or if you'd like to create your own manual mock, you can do something like this:

```js
jest.mock('Text', () => {
const RealComponent = require.requireActual('Text');
const RealComponent = jest.requireActual('Text');
const React = require('React');
class Text extends React.Component {
render() {
Expand Down
10 changes: 10 additions & 0 deletions website/versioned_docs/version-22.1/JestObjectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ The `jest` object is automatically in scope within every test file. The methods
- [`jest.runAllTimers()`](#jestrunalltimers)
- [`jest.advanceTimersByTime(msToRun)`](#jestadvancetimersbytimemstorun)
- [`jest.runOnlyPendingTimers()`](#jestrunonlypendingtimers)
- [`jest.requireActual()`](#jestrequireactual)
- [`jest.requireMock()`](#jestrequiremock)
- [`jest.setMock(moduleName, moduleExports)`](#jestsetmockmodulename-moduleexports)
- [`jest.setTimeout(timeout)`](#jestsettimeouttimeout)
- [`jest.useFakeTimers()`](#jestusefaketimers)
Expand Down Expand Up @@ -264,6 +266,14 @@ Executes only the macro-tasks that are currently pending (i.e., only the tasks t

This is useful for scenarios such as one where the module being tested schedules a `setTimeout()` whose callback schedules another `setTimeout()` recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time.

### `jest.requireActual(moduleName)`

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

### `jest.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

### `jest.setMock(moduleName, moduleExports)`

Explicitly supplies the mock object that the module system should return for the specified module.
Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-22.1/Troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ If a promise doesn't resolve at all, this error might be thrown:
- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.`
```

Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = require.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.
Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = jest.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.

If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout`

Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-22.1/TutorialReactNative.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ Or if you'd like to create your own manual mock, you can do something like this:

```js
jest.mock('Text', () => {
const RealComponent = require.requireActual('Text');
const RealComponent = jest.requireActual('Text');
const React = require('React');
class Text extends React.Component {
render() {
Expand Down
8 changes: 0 additions & 8 deletions website/versioned_docs/version-22.2/GlobalAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,14 +269,6 @@ describe.skip('my other beverage', () => {

Using `describe.skip` is often just an easier alternative to temporarily commenting out a chunk of tests.

### `require.requireActual(moduleName)`

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

### `require.requireMock(moduleName)`

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

### `test(name, fn, timeout)`

Also under the alias: `it(name, fn, timeout)`
Expand Down
Loading

0 comments on commit 4ec517e

Please sign in to comment.