diff --git a/website/versioned_docs/version-22.2.2/CLI.md b/website/versioned_docs/version-22.3/CLI.md similarity index 99% rename from website/versioned_docs/version-22.2.2/CLI.md rename to website/versioned_docs/version-22.3/CLI.md index fe1a0e801af7..340a8342dc5e 100644 --- a/website/versioned_docs/version-22.2.2/CLI.md +++ b/website/versioned_docs/version-22.3/CLI.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-cli +id: version-22.3-cli title: Jest CLI Options original_id: cli --- diff --git a/website/versioned_docs/version-22.2.2/Configuration.md b/website/versioned_docs/version-22.3/Configuration.md similarity index 96% rename from website/versioned_docs/version-22.2.2/Configuration.md rename to website/versioned_docs/version-22.3/Configuration.md index 748017643583..5aee81f35f2f 100644 --- a/website/versioned_docs/version-22.2.2/Configuration.md +++ b/website/versioned_docs/version-22.3/Configuration.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-configuration +id: version-22.3-configuration title: Configuring Jest original_id: configuration --- @@ -314,34 +314,6 @@ 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+** - -Default: `false` - -If you have [transformers](#transform-object-string-string) configured that emit -source maps, Jest will use them to try and map code coverage against the -original source code when writing [reports](#coveragereporters-array-string) and -checking [thresholds](#coveragethreshold-object). This is done on a best-effort -basis as some compile-to-JavaScript languages may provide more accurate source -maps than others. This can also be resource-intensive. If Jest is taking a long -time to calculate coverage at the end of a test run, try setting this option to -`false`. - -Both inline source maps and source maps returned directly from a transformer are -supported. Source map URLs are not supported because Jest may not be able to -locate them. To return source maps from a transformer, the `process` function -can return an object like the following. The `map` property may either be the -source map object, or the source map object as a string. - -```js -return { - code: 'the code', - map: 'the source map', -}; -``` - ### `moduleFileExtensions` [array] Default: `["js", "json", "jsx", "node"]` @@ -439,7 +411,8 @@ Specifies notification mode. Requires `notify: true`. * `success`: send a notification when tests pass. * `change`: send a notification when the status changed. * `success-change`: send a notification when tests pass or once when it fails. -* `failure-success`: send a notification when tests fails or once when it passes. +* `failure-success`: send a notification when tests fails or once when it + passes. ### `preset` [string] diff --git a/website/versioned_docs/version-22.2.2/Es6ClassMocks.md b/website/versioned_docs/version-22.3/Es6ClassMocks.md similarity index 61% rename from website/versioned_docs/version-22.2.2/Es6ClassMocks.md rename to website/versioned_docs/version-22.3/Es6ClassMocks.md index 0dae72c18a73..18e2008eb188 100644 --- a/website/versioned_docs/version-22.2.2/Es6ClassMocks.md +++ b/website/versioned_docs/version-22.3/Es6ClassMocks.md @@ -1,14 +1,22 @@ --- -id: version-22.2.2-es6-class-mocks +id: version-22.3-es6-class-mocks title: ES6 Class Mocks original_id: es6-class-mocks --- -Jest can be used to mock ES6 classes that are imported into files you want to test. -ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using [mock functions](MockFunctions.md). +Jest can be used to mock ES6 classes that are imported into files you want to +test. + +ES6 classes are constructor functions with some syntactic sugar. Therefore, any +mock for an ES6 class must be a function or an actual ES6 class (which is, +again, another function). So you can mock them using +[mock functions](MockFunctions.md). ## An ES6 Class Example -We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. + +We'll use a contrived example of a class that plays sound files, `SoundPlayer`, +and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock +`SoundPlayer` in our tests for `SoundPlayerConsumer`. ```javascript // sound-player.js @@ -42,9 +50,15 @@ export default class SoundPlayerConsumer { ## The 4 ways to create an ES6 class mock ### Automatic mock -Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with [mock functions](MockFunctions.md) that always return `undefined`. Method calls are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. -If you don't need to replace the implementation of the class, this is the easiest option to set up. For example: +Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can +use to spy on calls to the class constructor and all of its methods. It replaces +the ES6 class with a mock constructor, and replaces all of its methods with +[mock functions](MockFunctions.md) that always return `undefined`. Method calls +are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. + +If you don't need to replace the implementation of the class, this is the +easiest option to set up. For example: ```javascript import SoundPlayer from './sound-player'; @@ -61,7 +75,6 @@ it('We can check if the consumer called the class constructor', () => { expect(SoundPlayer).toHaveBeenCalledTimes(1); }); - it('We can check if the consumer called a method on the class instance', () => { // Show that mockClear() is working: expect(SoundPlayer).not.toHaveBeenCalled(); @@ -84,7 +97,10 @@ it('We can check if the consumer called a method on the class instance', () => { ``` ### Manual mock -Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. + +Create a [manual mock](ManualMocks.md) by saving a mock implementation in the +`__mocks__` folder. This allows you to specify the implementation, and it can be +used across test files. ```javascript // __mocks__/sound-player.js @@ -92,16 +108,17 @@ Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `_ // Import this named export into your test file: export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { - return { playSoundFile: mockPlaySoundFile }; + return {playSoundFile: mockPlaySoundFile}; }); export default mock; ``` Import the mock and the mock method shared by all instances: + ```javascript // sound-player-consumer.test.js -import SoundPlayer, { mockPlaySoundFile } from './sound-player'; +import SoundPlayer, {mockPlaySoundFile} from './sound-player'; import SoundPlayerConsumer from './sound-player-consumer'; jest.mock('./sound-player'); // SoundPlayer is now a mock constructor @@ -116,7 +133,6 @@ it('We can check if the consumer called the class constructor', () => { expect(SoundPlayer).toHaveBeenCalledTimes(1); }); - it('We can check if the consumer called a method on the class instance', () => { const soundPlayerConsumer = new SoundPlayerConsumer(); const coolSoundFileName = 'song.mp3'; @@ -125,27 +141,41 @@ it('We can check if the consumer called a method on the class instance', () => { }); ``` -### Calling [`jest.mock()`](JestObjectAPI.md#jestmockmodulename-factory-options) with the module factory parameter -`jest.mock(path, moduleFactory)` takes a **module factory** argument. A module factory is a function that returns the mock. +### Calling [`jest.mock()`](JestObjectAPI.md#jestmockmodulename-factory-options) with the module factory parameter + +`jest.mock(path, moduleFactory)` takes a **module factory** argument. A module +factory is a function that returns the mock. -In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). +In order to mock a constructor function, the module factory must return a +constructor function. In other words, the module factory must be a function that +returns a function - a higher-order function (HOF). ```javascript import SoundPlayer from './sound-player'; const mockPlaySoundFile = jest.fn(); jest.mock('./sound-player', () => { return jest.fn().mockImplementation(() => { - return { playSoundFile: mockPlaySoundFile }; + return {playSoundFile: mockPlaySoundFile}; }); }); ``` -A limitation with the factory parameter is that, since calls to `jest.mock()` are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'. It's up to you to guarantee that they will be initialized on time! +A limitation with the factory parameter is that, since calls to `jest.mock()` +are hoisted to the top of the file, it's not possible to first define a variable +and then use it in the factory. An exception is made for variables that start +with the word 'mock'. It's up to you to guarantee that they will be initialized +on time! ### Replacing the mock using [`mockImplementation()`](MockFunctionAPI.md#mockfnmockimplementationfn) or [`mockImplementationOnce()`](MockFunctionAPI.md#mockfnmockimplementationoncefn) -You can replace all of the above mocks in order to change the implementation, for a single test or all tests, by calling `mockImplementation()` on the existing mock. -Calls to jest.mock are hoisted to the top of the code. You can specify a mock later, e.g. in `beforeAll()`, by calling `mockImplementation()` (or `mockImplementationOnce()`) on the existing mock instead of using the factory parameter. This also allows you to change the mock between tests, if needed: +You can replace all of the above mocks in order to change the implementation, +for a single test or all tests, by calling `mockImplementation()` on the +existing mock. + +Calls to jest.mock are hoisted to the top of the code. You can specify a mock +later, e.g. in `beforeAll()`, by calling `mockImplementation()` (or +`mockImplementationOnce()`) on the existing mock instead of using the factory +parameter. This also allows you to change the mock between tests, if needed: ```javascript import SoundPlayer from './sound-player'; @@ -154,7 +184,11 @@ jest.mock('./sound-player'); describe('When SoundPlayer throws an error', () => { beforeAll(() => { SoundPlayer.mockImplementation(() => { - return { playSoundFile: () => { throw new Error('Test error')} }; + return { + playSoundFile: () => { + throw new Error('Test error'); + }, + }; }); }); @@ -166,10 +200,17 @@ describe('When SoundPlayer throws an error', () => { ``` ## In depth: Understanding mock constructor functions -Building your constructor function mock using `jest.fn().mockImplementation()` makes mocks appear more complicated than they really are. This section shows how you can create your own simple mocks to illustrate how mocking works. + +Building your constructor function mock using `jest.fn().mockImplementation()` +makes mocks appear more complicated than they really are. This section shows how +you can create your own simple mocks to illustrate how mocking works. ### Manual mock that is another ES6 class -If you define an ES6 class using the same filename as the mocked class in the `__mocks__` folder, it will serve as the mock. This class will be used in place of the real class. This allows you to inject a test implementation for the class, but does not provide a way to spy on calls. + +If you define an ES6 class using the same filename as the mocked class in the +`__mocks__` folder, it will serve as the mock. This class will be used in place +of the real class. This allows you to inject a test implementation for the +class, but does not provide a way to spy on calls. For the contrived example, the mock might look like this: @@ -187,88 +228,120 @@ export default class SoundPlayer { ``` ### Simple mock using module factory parameter -The module factory function passed to `jest.mock(path, moduleFactory)` can be a HOF that returns a function*. This will allow calling `new` on the mock. Again, this allows you to inject different behavior for testing, but does not provide a way to spy on calls. -#### * Module factory function must return a function -In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). +The module factory function passed to `jest.mock(path, moduleFactory)` can be a +HOF that returns a function\*. This will allow calling `new` on the mock. Again, +this allows you to inject different behavior for testing, but does not provide a +way to spy on calls. + +#### \* Module factory function must return a function + +In order to mock a constructor function, the module factory must return a +constructor function. In other words, the module factory must be a function that +returns a function - a higher-order function (HOF). ```javascript jest.mock('./sound-player', () => { return function() { - return { playSoundFile: () => {} }; + return {playSoundFile: () => {}}; }; }); ``` -***Note: Arrow functions won't work*** +**_Note: Arrow functions won't work_** -Note that the mock can't be an arrow function because calling `new` on an arrow function is not allowed in Javascript. So this won't work: +Note that the mock can't be an arrow function because calling `new` on an arrow +function is not allowed in Javascript. So this won't work: ```javascript jest.mock('./sound-player', () => { - return () => { // Does not work; arrow functions can't be called with new - return { playSoundFile: () => {} }; + return () => { + // Does not work; arrow functions can't be called with new + return {playSoundFile: () => {}}; }; }); ``` -This will throw ***TypeError: _soundPlayer2.default is not a constructor***, unless the code is transpiled to ES5, e.g. by babel-preset-env. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.) +This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, +unless the code is transpiled to ES5, e.g. by babel-preset-env. (ES5 doesn't +have arrow functions nor classes, so both will be transpiled to plain +functions.) ## Keeping track of usage (spying on the mock) -Injecting a test implementation is helpful, but you will probably also want to test whether the class constructor and methods are called with the correct parameters. + +Injecting a test implementation is helpful, but you will probably also want to +test whether the class constructor and methods are called with the correct +parameters. ### Spying on the constructor -In order to track calls to the constructor, replace the function returned by the HOF with a Jest mock function. Create it with [`jest.fn()`](JestObjectAPI.md#jestfnimplementation), and then specify its implementation with `mockImplementation()`. +In order to track calls to the constructor, replace the function returned by the +HOF with a Jest mock function. Create it with +[`jest.fn()`](JestObjectAPI.md#jestfnimplementation), and then specify its +implementation with `mockImplementation()`. ```javascript import SoundPlayer from './sound-player'; jest.mock('./sound-player', () => { - // Works and lets you check for constructor calls: + // Works and lets you check for constructor calls: return jest.fn().mockImplementation(() => { - return { playSoundFile: () => {} }; + return {playSoundFile: () => {}}; }); }); ``` -This will let us inspect usage of our mocked class, using `SoundPlayer.mock.calls`: -`expect(SoundPlayer).toHaveBeenCalled();` -or near-equivalent: -`expect(SoundPlayer.mock.calls.length).toEqual(1);` +This will let us inspect usage of our mocked class, using +`SoundPlayer.mock.calls`: `expect(SoundPlayer).toHaveBeenCalled();` or +near-equivalent: `expect(SoundPlayer.mock.calls.length).toEqual(1);` ### Spying on methods of our class -Our mocked class will need to provide any member functions (`playSoundFile` in the example) that will be called during our tests, or else we'll get an error for calling a function that doesn't exist. But we'll probably want to also spy on calls to those methods, to ensure that they were called with the expected parameters. -A new object will be created each time the mock constructor function is called during tests. To spy on method calls in all of these objects, we populate `playSoundFile` with another mock function, and store a reference to that same mock function in our test file, so it's available during tests. +Our mocked class will need to provide any member functions (`playSoundFile` in +the example) that will be called during our tests, or else we'll get an error +for calling a function that doesn't exist. But we'll probably want to also spy +on calls to those methods, to ensure that they were called with the expected +parameters. + +A new object will be created each time the mock constructor function is called +during tests. To spy on method calls in all of these objects, we populate +`playSoundFile` with another mock function, and store a reference to that same +mock function in our test file, so it's available during tests. ```javascript import SoundPlayer from './sound-player'; const mockPlaySoundFile = jest.fn(); jest.mock('./sound-player', () => { return jest.fn().mockImplementation(() => { - return { playSoundFile: mockPlaySoundFile }; - // Now we can track calls to playSoundFile + return {playSoundFile: mockPlaySoundFile}; + // Now we can track calls to playSoundFile }); }); ``` The manual mock equivalent of this would be: + ```javascript // __mocks__/sound-player.js // Import this named export into your test file export const mockPlaySoundFile = jest.fn(); const mock = jest.fn().mockImplementation(() => { - return { playSoundFile: mockPlaySoundFile } + return {playSoundFile: mockPlaySoundFile}; }); export default mock; ``` -Usage is similar to the module factory function, except that you can omit the second argument from `jest.mock()`, and you must import the mocked method into your test file, since it is no longer defined there. Use the original module path for this; don't include `__mocks__`. +Usage is similar to the module factory function, except that you can omit the +second argument from `jest.mock()`, and you must import the mocked method into +your test file, since it is no longer defined there. Use the original module +path for this; don't include `__mocks__`. ### Cleaning up between tests -To clear the record of calls to the mock constructor function and its methods, we call [`mockClear()`](MockFunctionAPI.md#mockfnmockclear) in the `beforeEach()` function: + +To clear the record of calls to the mock constructor function and its methods, +we call [`mockClear()`](MockFunctionAPI.md#mockfnmockclear) in the +`beforeEach()` function: ```javascript beforeEach(() => { @@ -278,7 +351,9 @@ beforeEach(() => { ``` ## Complete example -Here's a complete test file which uses the module factory parameter to `jest.mock`: + +Here's a complete test file which uses the module factory parameter to +`jest.mock`: ```javascript // sound-player-consumer.test.js @@ -288,7 +363,7 @@ import SoundPlayer from './sound-player'; const mockPlaySoundFile = jest.fn(); jest.mock('./sound-player', () => { return jest.fn().mockImplementation(() => { - return { playSoundFile: mockPlaySoundFile }; + return {playSoundFile: mockPlaySoundFile}; }); }); @@ -314,5 +389,4 @@ it('We can check if the consumer called a method on the class instance', () => { soundPlayerConsumer.playSomethingCool(); expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName); }); - ``` diff --git a/website/versioned_docs/version-22.2.2/ExpectAPI.md b/website/versioned_docs/version-22.3/ExpectAPI.md similarity index 99% rename from website/versioned_docs/version-22.2.2/ExpectAPI.md rename to website/versioned_docs/version-22.3/ExpectAPI.md index ae1417376195..3985db9a85f2 100644 --- a/website/versioned_docs/version-22.2.2/ExpectAPI.md +++ b/website/versioned_docs/version-22.3/ExpectAPI.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-expect +id: version-22.3-expect title: Expect original_id: expect --- diff --git a/website/versioned_docs/version-22.2.2/GettingStarted.md b/website/versioned_docs/version-22.3/GettingStarted.md similarity index 99% rename from website/versioned_docs/version-22.2.2/GettingStarted.md rename to website/versioned_docs/version-22.3/GettingStarted.md index 6a11824f0b2c..2238758cacc0 100644 --- a/website/versioned_docs/version-22.2.2/GettingStarted.md +++ b/website/versioned_docs/version-22.3/GettingStarted.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-getting-started +id: version-22.3-getting-started title: Getting Started original_id: getting-started --- diff --git a/website/versioned_docs/version-22.2.2/GlobalAPI.md b/website/versioned_docs/version-22.3/GlobalAPI.md similarity index 99% rename from website/versioned_docs/version-22.2.2/GlobalAPI.md rename to website/versioned_docs/version-22.3/GlobalAPI.md index 0504de9fc449..ad5181dd7bdc 100644 --- a/website/versioned_docs/version-22.2.2/GlobalAPI.md +++ b/website/versioned_docs/version-22.3/GlobalAPI.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-api +id: version-22.3-api title: Globals original_id: api --- diff --git a/website/versioned_docs/version-22.2.2/JestObjectAPI.md b/website/versioned_docs/version-22.3/JestObjectAPI.md similarity index 99% rename from website/versioned_docs/version-22.2.2/JestObjectAPI.md rename to website/versioned_docs/version-22.3/JestObjectAPI.md index 4fa894542c40..d15d5eab9ae8 100644 --- a/website/versioned_docs/version-22.2.2/JestObjectAPI.md +++ b/website/versioned_docs/version-22.3/JestObjectAPI.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-jest-object +id: version-22.3-jest-object title: The Jest Object original_id: jest-object --- @@ -159,7 +159,7 @@ as well as all the modules that it imports._ Modules that are mocked with `jest.mock` are mocked only for the file that calls `jest.mock`. Another file that imports the module will get the original -implementation even if run after the test file that mocks the module. +implementation even if it runs after the test file that mocks the module. Returns the `jest` object for chaining. diff --git a/website/versioned_docs/version-22.2.2/JestPlatform.md b/website/versioned_docs/version-22.3/JestPlatform.md similarity index 99% rename from website/versioned_docs/version-22.2.2/JestPlatform.md rename to website/versioned_docs/version-22.3/JestPlatform.md index f59b4d15dbee..822590de2dd4 100644 --- a/website/versioned_docs/version-22.2.2/JestPlatform.md +++ b/website/versioned_docs/version-22.3/JestPlatform.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-jest-platform +id: version-22.3-jest-platform title: Jest Platform original_id: jest-platform --- diff --git a/website/versioned_docs/version-22.2.2/ManualMocks.md b/website/versioned_docs/version-22.3/ManualMocks.md similarity index 99% rename from website/versioned_docs/version-22.2.2/ManualMocks.md rename to website/versioned_docs/version-22.3/ManualMocks.md index b8064269f198..eb2030bd5681 100644 --- a/website/versioned_docs/version-22.2.2/ManualMocks.md +++ b/website/versioned_docs/version-22.3/ManualMocks.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-manual-mocks +id: version-22.3-manual-mocks title: Manual Mocks original_id: manual-mocks --- diff --git a/website/versioned_docs/version-22.2.2/MigrationGuide.md b/website/versioned_docs/version-22.3/MigrationGuide.md similarity index 97% rename from website/versioned_docs/version-22.2.2/MigrationGuide.md rename to website/versioned_docs/version-22.3/MigrationGuide.md index eae7f4d927da..0daca81d6f8a 100644 --- a/website/versioned_docs/version-22.2.2/MigrationGuide.md +++ b/website/versioned_docs/version-22.3/MigrationGuide.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-migration-guide +id: version-22.3-migration-guide title: Migrating to Jest original_id: migration-guide --- diff --git a/website/versioned_docs/version-22.2.2/MockFunctionAPI.md b/website/versioned_docs/version-22.3/MockFunctionAPI.md similarity index 99% rename from website/versioned_docs/version-22.2.2/MockFunctionAPI.md rename to website/versioned_docs/version-22.3/MockFunctionAPI.md index 36000787edc9..3d118374345a 100644 --- a/website/versioned_docs/version-22.2.2/MockFunctionAPI.md +++ b/website/versioned_docs/version-22.3/MockFunctionAPI.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-mock-function-api +id: version-22.3-mock-function-api title: Mock Functions original_id: mock-function-api --- diff --git a/website/versioned_docs/version-22.2.2/MockFunctions.md b/website/versioned_docs/version-22.3/MockFunctions.md similarity index 99% rename from website/versioned_docs/version-22.2.2/MockFunctions.md rename to website/versioned_docs/version-22.3/MockFunctions.md index 81f13e9e8b21..59c0468d5fdc 100644 --- a/website/versioned_docs/version-22.2.2/MockFunctions.md +++ b/website/versioned_docs/version-22.3/MockFunctions.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-mock-functions +id: version-22.3-mock-functions title: Mock Functions original_id: mock-functions --- diff --git a/website/versioned_docs/version-22.3/MongoDB.md b/website/versioned_docs/version-22.3/MongoDB.md new file mode 100644 index 000000000000..3f0a1b126c3c --- /dev/null +++ b/website/versioned_docs/version-22.3/MongoDB.md @@ -0,0 +1,128 @@ +--- +id: version-22.3-mongodb +title: Using with MongoDB +original_id: mongodb +--- + +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and +[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can +work smoothly with [MongoDB](https://www.mongodb.com/). + +## A jest-mongodb example + +The basic idea is to: + +1. Spin up in-memory mongodb server +2. Export a global variable with mongo URI +3. Write tests for queries / aggregations using a real database ✨ +4. Shut down mongodb server using Global Teardown + +Here's an example of the GlobalSetup script + +```js +// setup.js +const MongodbMemoryServer = require('mongodb-memory-server'); + +const MONGO_DB_NAME = 'jest'; +const mongod = new MongodbMemoryServer.default({ + instance: { + dbName: MONGO_DB_NAME, + }, + binary: { + version: '3.2.19', + }, +}); + +module.exports = function() { + global.__MONGOD__ = mongod; + global.__MONGO_DB_NAME__ = MONGO_DB_NAME; +}; +``` + +Then we need a custom Test Environment for Mongo + +```js +// mongo-environment.js +class MongoEnvironment extends NodeEnvironment { + constructor(config) { + super(config); + } + + async setup() { + console.log('Setup MongoDB Test Environment'); + + this.global.__MONGO_URI__ = await global.__MONGOD__.getConnectionString(); + this.global.__MONGO_DB_NAME__ = global.__MONGO_DB_NAME__; + + await super.setup(); + } + + async teardown() { + console.log('Teardown MongoDB Test Environment'); + + await super.teardown(); + } + + runScript(script) { + return super.runScript(script); + } +} +``` + +Finally we can shut down mongodb server + +```js +// teardown.js +module.exports = async function() { + await global.__MONGOD__.stop(); +}; +``` + +With all the things set up, we can now write our tests like this: + +```js +// test.js +const {MongoClient} = require('mongodb'); + +let connection; +let db; + +beforeAll(async () => { + connection = await MongoClient.connect(global.__MONGO_URI__); + db = await connection.db(global.__MONGO_DB_NAME__); +}); + +afterAll(async () => { + await connection.close(); + await db.close(); +}); + +it('should aggregate docs from collection', async () => { + const files = db.collection('files'); + + await files.insertMany([ + {type: 'Document'}, + {type: 'Video'}, + {type: 'Image'}, + {type: 'Document'}, + {type: 'Image'}, + {type: 'Document'}, + ]); + + const topFiles = await files + .aggregate([ + {$group: {_id: '$type', count: {$sum: 1}}}, + {$sort: {count: -1}}, + ]) + .toArray(); + + expect(topFiles).toEqual([ + {_id: 'Document', count: 3}, + {_id: 'Image', count: 2}, + {_id: 'Video', count: 1}, + ]); +}); +``` + +Here's the code of +[full working example](https://github.com/vladgolubev/jest-mongodb). diff --git a/website/versioned_docs/version-22.2.2/MoreResources.md b/website/versioned_docs/version-22.3/MoreResources.md similarity index 90% rename from website/versioned_docs/version-22.2.2/MoreResources.md rename to website/versioned_docs/version-22.3/MoreResources.md index f3e5777fd661..3a47bba502b9 100644 --- a/website/versioned_docs/version-22.2.2/MoreResources.md +++ b/website/versioned_docs/version-22.3/MoreResources.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-more-resources +id: version-22.3-more-resources title: More Resources original_id: more-resources --- @@ -33,9 +33,7 @@ projects. Ask questions and find answers from other Jest users like you. [Reactiflux](http://www.reactiflux.com/) is a Discord chat where a lot of Jest -discussion happens. Check out the -[#jest](https://discordapp.com/channels/102860784329052160/103622435865104384) -channel. +discussion happens. Check out the [#jest](https://discord.gg/MWRhKCj) channel. Follow the [Jest Twitter account](https://twitter.com/fbjest) and [blog](/jest/blog/) to find out what's happening in the world of Jest. diff --git a/website/versioned_docs/version-22.2.2/Puppeteer.md b/website/versioned_docs/version-22.3/Puppeteer.md similarity index 98% rename from website/versioned_docs/version-22.2.2/Puppeteer.md rename to website/versioned_docs/version-22.3/Puppeteer.md index 55eb0abc4ca3..496f49652500 100644 --- a/website/versioned_docs/version-22.2.2/Puppeteer.md +++ b/website/versioned_docs/version-22.3/Puppeteer.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-puppeteer +id: version-22.3-puppeteer title: Using with puppeteer original_id: puppeteer --- diff --git a/website/versioned_docs/version-22.2.2/SetupAndTeardown.md b/website/versioned_docs/version-22.3/SetupAndTeardown.md similarity index 99% rename from website/versioned_docs/version-22.2.2/SetupAndTeardown.md rename to website/versioned_docs/version-22.3/SetupAndTeardown.md index 88b38ca21965..ad97a201d4dd 100644 --- a/website/versioned_docs/version-22.2.2/SetupAndTeardown.md +++ b/website/versioned_docs/version-22.3/SetupAndTeardown.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-setup-teardown +id: version-22.3-setup-teardown title: Setup and Teardown original_id: setup-teardown --- diff --git a/website/versioned_docs/version-22.2.2/SnapshotTesting.md b/website/versioned_docs/version-22.3/SnapshotTesting.md similarity index 98% rename from website/versioned_docs/version-22.2.2/SnapshotTesting.md rename to website/versioned_docs/version-22.3/SnapshotTesting.md index 73eeb0725f68..33b1ae2f7c7d 100644 --- a/website/versioned_docs/version-22.2.2/SnapshotTesting.md +++ b/website/versioned_docs/version-22.3/SnapshotTesting.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-snapshot-testing +id: version-22.3-snapshot-testing title: Snapshot Testing original_id: snapshot-testing --- @@ -128,9 +128,9 @@ Failed snapshots can also be updated interactively in watch mode: ![](/jest/img/content/interactiveSnapshot.png) -Once you enter Interactive Snapshot Mode, Jest will step you through -the failed snapshots one test suite at a time and give you the opportunity to -review the failed output. +Once you enter Interactive Snapshot Mode, Jest will step you through the failed +snapshots one test suite at a time and give you the opportunity to review the +failed output. From here you can choose to update that snapshot or skip to the next: diff --git a/website/versioned_docs/version-22.2.2/TestingAsyncCode.md b/website/versioned_docs/version-22.3/TestingAsyncCode.md similarity index 99% rename from website/versioned_docs/version-22.2.2/TestingAsyncCode.md rename to website/versioned_docs/version-22.3/TestingAsyncCode.md index 3fb72cd65489..f8f8073b219f 100644 --- a/website/versioned_docs/version-22.2.2/TestingAsyncCode.md +++ b/website/versioned_docs/version-22.3/TestingAsyncCode.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-asynchronous +id: version-22.3-asynchronous title: Testing Asynchronous Code original_id: asynchronous --- diff --git a/website/versioned_docs/version-22.2.2/TestingFrameworks.md b/website/versioned_docs/version-22.3/TestingFrameworks.md similarity index 97% rename from website/versioned_docs/version-22.2.2/TestingFrameworks.md rename to website/versioned_docs/version-22.3/TestingFrameworks.md index 7050c90080c9..fdf933080787 100644 --- a/website/versioned_docs/version-22.2.2/TestingFrameworks.md +++ b/website/versioned_docs/version-22.3/TestingFrameworks.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-testing-frameworks +id: version-22.3-testing-frameworks title: Testing Web Frameworks original_id: testing-frameworks --- diff --git a/website/versioned_docs/version-22.2.2/TimerMocks.md b/website/versioned_docs/version-22.3/TimerMocks.md similarity index 99% rename from website/versioned_docs/version-22.2.2/TimerMocks.md rename to website/versioned_docs/version-22.3/TimerMocks.md index c63ead51f482..6aad2822ff33 100644 --- a/website/versioned_docs/version-22.2.2/TimerMocks.md +++ b/website/versioned_docs/version-22.3/TimerMocks.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-timer-mocks +id: version-22.3-timer-mocks title: Timer Mocks original_id: timer-mocks --- diff --git a/website/versioned_docs/version-22.2.2/Troubleshooting.md b/website/versioned_docs/version-22.3/Troubleshooting.md similarity index 99% rename from website/versioned_docs/version-22.2.2/Troubleshooting.md rename to website/versioned_docs/version-22.3/Troubleshooting.md index 967b55dcca0f..0eb0426f1840 100644 --- a/website/versioned_docs/version-22.2.2/Troubleshooting.md +++ b/website/versioned_docs/version-22.3/Troubleshooting.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-troubleshooting +id: version-22.3-troubleshooting title: Troubleshooting original_id: troubleshooting --- diff --git a/website/versioned_docs/version-22.2.2/TutorialAsync.md b/website/versioned_docs/version-22.3/TutorialAsync.md similarity index 99% rename from website/versioned_docs/version-22.2.2/TutorialAsync.md rename to website/versioned_docs/version-22.3/TutorialAsync.md index 1f1cb31668eb..c67e65c18cf5 100644 --- a/website/versioned_docs/version-22.2.2/TutorialAsync.md +++ b/website/versioned_docs/version-22.3/TutorialAsync.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-tutorial-async +id: version-22.3-tutorial-async title: An Async Example original_id: tutorial-async --- diff --git a/website/versioned_docs/version-22.2.2/TutorialReact.md b/website/versioned_docs/version-22.3/TutorialReact.md similarity index 99% rename from website/versioned_docs/version-22.2.2/TutorialReact.md rename to website/versioned_docs/version-22.3/TutorialReact.md index fd28af0fabec..19703e0ac2f7 100644 --- a/website/versioned_docs/version-22.2.2/TutorialReact.md +++ b/website/versioned_docs/version-22.3/TutorialReact.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-tutorial-react +id: version-22.3-tutorial-react title: Testing React Apps original_id: tutorial-react --- diff --git a/website/versioned_docs/version-22.2.2/TutorialReactNative.md b/website/versioned_docs/version-22.3/TutorialReactNative.md similarity index 95% rename from website/versioned_docs/version-22.2.2/TutorialReactNative.md rename to website/versioned_docs/version-22.3/TutorialReactNative.md index 4b08d47690da..5b5ae40a69e6 100644 --- a/website/versioned_docs/version-22.2.2/TutorialReactNative.md +++ b/website/versioned_docs/version-22.3/TutorialReactNative.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-tutorial-react-native +id: version-22.3-tutorial-react-native title: Testing React Native Apps original_id: tutorial-react-native --- @@ -83,11 +83,9 @@ the component and capture the rendered output and create a snapshot file: ```javascript // __tests__/Intro-test.js -import 'react-native'; import React from 'react'; import Intro from '../Intro'; -// Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; test('renders correctly', () => { @@ -251,17 +249,6 @@ real device and then modeling a manual mock after the real module. If you end up mocking the same modules over and over it is recommended to define these mocks in a separate file and add it to the list of `setupFiles`. -### require react-native before the test renderer - -Currently it is required to require react-native before loading the test -renderer: - -```js -import 'react-native'; -// Require after react-native -import renderer from 'react-test-renderer'; -``` - ### `@providesModule` If you'd like to use Facebook's `@providesModule` module system through an npm diff --git a/website/versioned_docs/version-22.2.2/TutorialjQuery.md b/website/versioned_docs/version-22.3/TutorialjQuery.md similarity index 98% rename from website/versioned_docs/version-22.2.2/TutorialjQuery.md rename to website/versioned_docs/version-22.3/TutorialjQuery.md index fff2a8fc5f55..dfcd913c4e18 100644 --- a/website/versioned_docs/version-22.2.2/TutorialjQuery.md +++ b/website/versioned_docs/version-22.3/TutorialjQuery.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-tutorial-jquery +id: version-22.3-tutorial-jquery title: DOM Manipulation original_id: tutorial-jquery --- diff --git a/website/versioned_docs/version-22.2.2/UsingMatchers.md b/website/versioned_docs/version-22.3/UsingMatchers.md similarity index 99% rename from website/versioned_docs/version-22.2.2/UsingMatchers.md rename to website/versioned_docs/version-22.3/UsingMatchers.md index 1698892a1b37..cdd506bcb501 100644 --- a/website/versioned_docs/version-22.2.2/UsingMatchers.md +++ b/website/versioned_docs/version-22.3/UsingMatchers.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-using-matchers +id: version-22.3-using-matchers title: Using Matchers original_id: using-matchers --- diff --git a/website/versioned_docs/version-22.2.2/Webpack.md b/website/versioned_docs/version-22.3/Webpack.md similarity index 99% rename from website/versioned_docs/version-22.2.2/Webpack.md rename to website/versioned_docs/version-22.3/Webpack.md index e7acd7b0d43f..1157b6888ad9 100644 --- a/website/versioned_docs/version-22.2.2/Webpack.md +++ b/website/versioned_docs/version-22.3/Webpack.md @@ -1,5 +1,5 @@ --- -id: version-22.2.2-webpack +id: version-22.3-webpack title: Using with webpack original_id: webpack --- diff --git a/website/versioned_sidebars/version-22.2.2-sidebars.json b/website/versioned_sidebars/version-22.2.2-sidebars.json deleted file mode 100644 index 9abbcc0624c0..000000000000 --- a/website/versioned_sidebars/version-22.2.2-sidebars.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "version-22.2.2-docs": { - "Introduction": [ - "version-22.2.2-getting-started", - "version-22.2.2-using-matchers", - "version-22.2.2-asynchronous", - "version-22.2.2-setup-teardown", - "version-22.2.2-mock-functions", - "version-22.2.2-jest-platform", - "version-22.2.2-more-resources" - ], - "Guides": [ - "version-22.2.2-snapshot-testing", - "version-22.2.2-tutorial-async", - "version-22.2.2-timer-mocks", - "version-22.2.2-manual-mocks", - "version-22.2.2-es6-class-mocks", - "version-22.2.2-webpack", - "version-22.2.2-puppeteer", - "version-22.2.2-migration-guide", - "version-22.2.2-troubleshooting" - ], - "Framework Guides": [ - "version-22.2.2-tutorial-react", - "version-22.2.2-tutorial-react-native", - "version-22.2.2-testing-frameworks" - ], - "API Reference": [ - "version-22.2.2-api", - "version-22.2.2-expect", - "version-22.2.2-mock-function-api", - "version-22.2.2-jest-object", - "version-22.2.2-configuration", - "version-22.2.2-cli" - ] - } -} diff --git a/website/versioned_sidebars/version-22.3-sidebars.json b/website/versioned_sidebars/version-22.3-sidebars.json new file mode 100644 index 000000000000..1280e7623454 --- /dev/null +++ b/website/versioned_sidebars/version-22.3-sidebars.json @@ -0,0 +1,38 @@ +{ + "version-22.3-docs": { + "Introduction": [ + "version-22.3-getting-started", + "version-22.3-using-matchers", + "version-22.3-asynchronous", + "version-22.3-setup-teardown", + "version-22.3-mock-functions", + "version-22.3-jest-platform", + "version-22.3-more-resources" + ], + "Guides": [ + "version-22.3-snapshot-testing", + "version-22.3-tutorial-async", + "version-22.3-timer-mocks", + "version-22.3-manual-mocks", + "version-22.3-es6-class-mocks", + "version-22.3-webpack", + "version-22.3-puppeteer", + "version-22.3-mongodb", + "version-22.3-migration-guide", + "version-22.3-troubleshooting" + ], + "Framework Guides": [ + "version-22.3-tutorial-react", + "version-22.3-tutorial-react-native", + "version-22.3-testing-frameworks" + ], + "API Reference": [ + "version-22.3-api", + "version-22.3-expect", + "version-22.3-mock-function-api", + "version-22.3-jest-object", + "version-22.3-configuration", + "version-22.3-cli" + ] + } +} diff --git a/website/versions.json b/website/versions.json index e37c488987bb..092f6cd55002 100644 --- a/website/versions.json +++ b/website/versions.json @@ -1 +1,3 @@ -["22.2.2"] +[ + "22.3" +]