Skip to content

Latest commit

 

History

History
74 lines (48 loc) · 3.13 KB

testing-with-jest.md

File metadata and controls

74 lines (48 loc) · 3.13 KB

Switched Testing to Jest

The first part is a brief log of migrating the tests from the mocha tests in the book to jest. Note the second part about improving the tests with proper Mongo integration and Snapshots.

Installation

npm install --save-dev babel-cli babel-preset-env jest supertest superagent

Had to adapt the Express inclusion and the expect matchers a little bit to migrate to jest.

Adapt jest config to work with mongoose

console.warn
    Mongoose: looks like you're trying to test a Mongoose app with Jest's default jsdom test environment. Please make sure you read Mongoose's docs on configuring Jest to test Node.js apps: http://mongoosejs.com/docs/jest.html

Added jest config as described to package.json:

"testEnvironment": "node"

Jest Command line Options

jest --watch

Links

Using MongoDB in Tests

The mechanism described in the book to use a test database has two disadvantages:

  • test runs are dependent on an available mongo instance.
  • the db connection logic in main.js/app.js is used and redirected if an environment variable is present. As this is not enforced, this solution is prone to errors.

switching to the test db depends on setting an environment variable to switch to the test database. This is not enforced in the tests, and if forgotten, tests will possibly manipulate the main database. Although this would probably only happen on a developer's machine and not in production, it doesn't seem like a good idea.

To set up testing with mongo properly, I've followed the Documentation in https://jestjs.io/docs/en/mongodb This uses an in-memory db for the tests.

Steps taken (also refer to the commits:)

  • npm install @shelf/jest-mongodb --save-dev
  • adapted jest configuration in package.json
  • added test/jest-mongodb-config.js
  • created test/api/mongo.test.js
  • moved db connection from app.js to main.js - the tests only require app.js
  • created a proper db setup in test/commonJest.js

Documentation

Snapshot Testing

Jests has a neat functionality called "Snapshot Testing" - it basically stores a serialized output in the source code and diffs against the stored version.

We will use this later on for testing React components. Creating snapshots of complete HTML-Pages generated by Express will probably not work well on larger projects, but it is actually quite useful to get off the ground testing with jest easily.

For the snapshots to work, I needed to use a fixed object id in testing, which works only with the in-memory db solution described above. I've used an api test to figure out mongoose behaviour: test/api/mongoose/setId.test.js

See test/snapshots/ for examples, especially test/snapshots/courses/index.test.js for an example fixing the object ids in mongo.