How to write unit tests
Unit tests are tests that run only on the server side, and which focus on verifying that the RadGrad data model (i.e. the set of Collection classes in the api/ directory) work as intended.
To write unit tests, we use the Mocha test runner and Chai Expect Assertions. We follow recommendations from the Meteor Guide Unit Testing Chapter.
Each collection class contains its tests in a "sibling" file. For example, unit tests for CourseCollection.js are located in CourseCollection.test.js.
The test file names are important: Meteor wants unit tests to be in files with the suffix test.js
.
Many tests require the database to be initialized with test values. RadGrad provides "database fixture" files for this purpose. See the DB fixture chapter for more details.
Running all unit tests
To invoke all of the unit tests, use this command:
Here's what an abbreviated, sample output looks like:
There should be no server or client failures listed. Indeed, there will also be no client tests at all. In RadGrad, all unit tests occur on the server side.
Run a subset of unit tests
To run a subset of the tests you can set the environment variable MOCHA_GREP
. If MOCHA_GREP
matches the name of the test as defined in the describe
statement those tests will run.
MacOS and Linux
For example:
Windows
Default structure of a unit test
RadGrad collection have five required methods.
- define: Creates a new document in the collection. Returns the document's id.
- update: Updates a document in the collection.
- removeIt: Removes a document from the collection.
- dumpOne: Returns a JSON object suitable for defining the document.
- checkIntegrity: Checks each document in the collection for integrity. Returns an array of problems.
All of our unit test have a standard format. We ensure that, at a minimum, we test the five methods.
To help simplify the testing process, we create one or more functions to make a sample document for the collection. These functions are defined and exported in a file named Sample
.ts. The SampleCourses.ts defines and exports three functions,makeSampleCourse
, makeSampleCourseInstance
, and getRandomGrade
. We use these functions in other tests.The standard format looks something like:
The above five tests ensure that our collection's basic functionality works. If you define other methods for your collection then you should create more tests after the base five. For example, the CourseCollection tests has additional tests.