Skip to content

Commit

Permalink
Merge branch 'master' of github.com:d7my11/jest into iterable-equalit…
Browse files Browse the repository at this point in the history
…y-within-object
  • Loading branch information
d7my11 committed Apr 22, 2019
2 parents 87c4e62 + cd11240 commit 8fc238f
Show file tree
Hide file tree
Showing 57 changed files with 1,509 additions and 1,585 deletions.
11 changes: 10 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,28 @@

### Features

- `[jest-circus]` Bind to Circus events via an optional event handler on any custom env ([#8344](https://github.com/facebook/jest/pull/8344)
- `[expect]` Improve report when matcher fails, part 15 ([#8281](https://github.com/facebook/jest/pull/8281))
- `[jest-cli]` Update `--forceExit` and "did not exit for one second" message colors ([#8329](https://github.com/facebook/jest/pull/8329))
- `[expect]` Improve report when matcher fails, part 16 ([#8306](https://github.com/facebook/jest/pull/8306))
- `[jest-runner]` Pass docblock pragmas to TestEnvironment constructor ([#8320](https://github.com/facebook/jest/pull/8320))
- `[docs]` Add DynamoDB guide ([#8319](https://github.com/facebook/jest/pull/8319))
- `[expect]` Improve report when matcher fails, part 17 ([#8349](https://github.com/facebook/jest/pull/8349))

### Fixes

- `[jest-each]` Fix bug with placeholder values ([#8289](https://github.com/facebook/jest/pull/8289))
- `[jest-snapshot]` Inline snapshots: do not indent empty lines ([#8277](https://github.com/facebook/jest/pull/8277))
- `[@jest/runtime, @jest/transform]` Allow custom transforms for JSON dependencies ([#2578](https://github.com/facebook/jest/pull/2578))
- `[jest-core]` Make `detectOpenHandles` imply `runInBand` ([#8283](https://github.com/facebook/jest/pull/8283))
- `[jest-haste-map]` Fix the `mapper` option which was incorrectly ignored ([#8299](https://github.com/facebook/jest/pull/8299))
- `[jest-jasmine2]` Fix describe return value warning being shown if the describe function throws ([#8335](https://github.com/facebook/jest/pull/8335))
- `[jest-environment-jsdom]` Re-declare global prototype of JSDOMEnvironment ([#8352](https://github.com/facebook/jest/pull/8352))
- `[expect]` Fix `iterableEquality` ignores other properties ([#8359](https://github.com/facebook/jest/pull/8359))

### Chore & Maintenance

- `[expect]` Fix label and add opposite assertion for toEqual tests ([#8288](https://github.com/facebook/jest/pull/8288))
- `[docs]` Mention Jest MongoDB Preset ([#8318](https://github.com/facebook/jest/pull/8318))

### Performance

Expand Down
20 changes: 18 additions & 2 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,10 @@ test('use jsdom in this test file', () => {

You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables.

The class may optionally expose a `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/master/packages/jest-circus).

Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with it's value set to an empty string. If the pragma is not present, it will not be present in the object.

_Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment._

Example:
Expand All @@ -870,15 +874,21 @@ Example:
const NodeEnvironment = require('jest-environment-node');

class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
constructor(config, {testPath, docblockPragmas}) {
super(config, context);
this.testPath = context.testPath;
this.testPath = testPath;
this.docblockPragmas = docblockPragmas;
}

async setup() {
await super.setup();
await someSetupTasks(this.testPath);
this.global.someGlobalObject = createGlobalObject();

// Will trigger if docblock contains @my-custom-pragma my-pragma-value
if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
// ...
}
}

async teardown() {
Expand All @@ -890,6 +900,12 @@ class CustomEnvironment extends NodeEnvironment {
runScript(script) {
return super.runScript(script);
}

handleTestEvent(event, state) {
if (event.name === 'test_start') {
// ...
}
}
}

module.exports = CustomEnvironment;
Expand Down
81 changes: 81 additions & 0 deletions docs/DynamoDB.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
id: dynamodb
title: Using with DynamoDB
---

With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [DynamoDB](https://aws.amazon.com/dynamodb/).

## Use jest-dynamodb Preset

[Jest DynamoDB](https://github.com/shelfio/jest-dynamodb) provides all required configuration to run your tests using DynamoDB.

1. First install `@shelf/jest-dynamodb`

```
yarn add @shelf/jest-dynamodb --dev
```

2. Specify preset in your Jest configuration:

```json
{
"preset": "@shelf/jest-dynamodb"
}
```

3. Create `jest-dynamodb-config.js` and define DynamoDB tables

See [Create Table API](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property)

```js
module.exports = {
tables: [
{
TableName: `files`,
KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}],
AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}],
ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1},
},
// etc
],
};
```

4. Configure DynamoDB client

```js
const {DocumentClient} = require('aws-sdk/clients/dynamodb');

const isTest = process.env.JEST_WORKER_ID;
const config = {
convertEmptyValues: true,
...(isTest && {
endpoint: 'localhost:8000',
sslEnabled: false,
region: 'local-env',
}),
};

const ddb = new DocumentClient(config);
```

5. Write tests

```js
it('should insert item into table', async () => {
await ddb
.put({TableName: 'files', Item: {id: '1', hello: 'world'}})
.promise();

const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise();

expect(Item).toEqual({
id: '1',
hello: 'world',
});
});
```

There's no need to load any dependencies.

See [documentation](https://github.com/shelfio/jest-dynamodb) for details.
6 changes: 0 additions & 6 deletions docs/ExpectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -1062,12 +1062,6 @@ describe('toMatchObject applied to arrays', () => {
expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]);
});

// .arrayContaining "matches a received array which contains elements that
// are *not* in the expected array"
test('.toMatchObject does not allow extra elements', () => {
expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}]);
});

test('.toMatchObject is called for each elements, so extra object properties are okay', () => {
expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([
{foo: 'bar'},
Expand Down
8 changes: 1 addition & 7 deletions docs/MigrationGuide.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,10 @@ If you'd like to try out Jest with an existing codebase, there are a number of w

If you are using [AVA](https://github.com/avajs/ava), [Chai](https://github.com/chaijs/chai), [Expect.js (by Automattic)](https://github.com/Automattic/expect.js), [Jasmine](https://github.com/jasmine/jasmine), [Mocha](https://github.com/mochajs/mocha), [proxyquire](https://github.com/thlorenz/proxyquire), [Should.js](https://github.com/shouldjs/should.js) or [Tape](https://github.com/substack/tape) you can use the third-party [jest-codemods](https://github.com/skovhus/jest-codemods) to do most of the dirty migration work. It runs a code transformation on your codebase using [jscodeshift](https://github.com/facebook/jscodeshift).

Install Jest Codemods with `yarn` by running:

```bash
yarn global add jest-codemods
```

To transform your existing tests, navigate to the project containing the tests and run:

```bash
jest-codemods
npx jest-codemods
```

More information can be found at [https://github.com/skovhus/jest-codemods](https://github.com/skovhus/jest-codemods).
155 changes: 35 additions & 120 deletions docs/MongoDB.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,142 +5,57 @@ title: Using with 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
## Use jest-mongodb Preset

The basic idea is to:
[Jest MongoDB](https://github.com/shelfio/jest-mongodb) provides all required configuration to run your tests using MongoDB.

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
1. First install `@shelf/jest-mongodb`

Here's an example of the GlobalSetup script

```js
// setup.js
const path = require('path');

const fs = require('fs');

const {MongoMemoryServer} = require('mongodb-memory-server');

const globalConfigPath = path.join(__dirname, 'globalConfig.json');

const mongod = new MongoMemoryServer({
autoStart: false,
});

module.exports = async () => {
if (!mongod.isRunning) {
await mongod.start();
}

const mongoConfig = {
mongoDBName: 'jest',
mongoUri: await mongod.getConnectionString(),
};

// Write global config to disk because all tests run in different contexts.
fs.writeFileSync(globalConfigPath, JSON.stringify(mongoConfig));

// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
};
```
yarn add @shelf/jest-mongodb --dev
```

Then we need a custom Test Environment for Mongo

```js
// mongo-environment.js
const NodeEnvironment = require('jest-environment-node');

const path = require('path');

const fs = require('fs');

const globalConfigPath = path.join(__dirname, 'globalConfig.json');

class MongoEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
}

async setup() {
console.log('Setup MongoDB Test Environment');

const globalConfig = JSON.parse(fs.readFileSync(globalConfigPath, 'utf-8'));

this.global.__MONGO_URI__ = globalConfig.mongoUri;
this.global.__MONGO_DB_NAME__ = globalConfig.mongoDBName;

await super.setup();
}

async teardown() {
console.log('Teardown MongoDB Test Environment');

await super.teardown();
}
2. Specify preset in your Jest configuration:

runScript(script) {
return super.runScript(script);
}
```json
{
"preset": "@shelf/jest-mongodb"
}

module.exports = MongoEnvironment;
```

Finally we can shut down mongodb server
3. Write your test

```js
// teardown.js
module.exports = async function() {
await global.__MONGOD__.stop();
};
```
const {MongoClient} = require('mongodb');

With all the things set up, we can now write our tests like this:
describe('insert', () => {
let connection;
let db;

```js
// test.js
const {MongoClient} = require('mongodb');
beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
});

let connection;
let db;
afterAll(async () => {
await connection.close();
await db.close();
});

beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__);
db = await connection.db(global.__MONGO_DB_NAME__);
});
it('should insert a doc into collection', async () => {
const users = db.collection('users');

afterAll(async () => {
await connection.close();
await db.close();
});
const mockUser = {_id: 'some-user-id', name: 'John'};
await users.insertOne(mockUser);

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},
]);
const insertedUser = await users.findOne({_id: 'some-user-id'});
expect(insertedUser).toEqual(mockUser);
});
});
```

There's no need to load any dependencies.

See [documentation](https://github.com/shelfio/jest-mongodb) for details (configuring MongoDB version, etc).
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ PASS foo/bar.spec.js
✓ foo
Force exiting Jest
Have you considered using \`--detectOpenHandles\` to detect async operations that kept running after all tests finished?
Force exiting Jest: Have you considered using \`--detectOpenHandles\` to detect async operations that kept running after all tests finished?
`;

exports[`CLI accepts exact file names if matchers matched 2`] = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ PASS __tests__/a-banana.js
✓ banana
Force exiting Jest
Have you considered using \`--detectOpenHandles\` to detect async operations that kept running after all tests finished?
Force exiting Jest: Have you considered using \`--detectOpenHandles\` to detect async operations that kept running after all tests finished?
`;

exports[`prints console.logs when run with forceExit 2`] = `
Expand Down
Loading

0 comments on commit 8fc238f

Please sign in to comment.