DEV Community

azu
azu

Posted on

Write Snapshots testing without Jest

Jest is useful tool for snapshot testing. Snapshot testing is used in many library.
For example, prettier use snapshot testings.

I want to write snapshots testing without Jest.
In such a case, I often use following template code.

Write snapshot testing

For example, following code work on Mocha.

  • Input: json
  • Ouput: json

snapshot-test.js:

const fs = require("fs");
const path = require("path");
const assert = require("assert");
const fixturesDir = path.join(__dirname, "snapshots");
// TODO: your transform function
const transform = require("../transform");

describe("Snapshot testing", () => {
  fs.readdirSync(fixturesDir)
    .map(caseName => {
      const normalizedTestName = caseName.replace(/-/g, " ");
      it(`Test ${normalizedTestName}`, function() {
        const fixtureDir = path.join(fixturesDir, caseName);
        const actualFilePath = path.join(fixtureDir, "input.json");
        const actualContent = JSON.parse(fs.readFileSync(actualFilePath, "utf-8"));
        const actual = transform(actualContent);
        const expectedFilePath = path.join(fixtureDir, "output.json");
        // Usage: update snapshots
        // UPDATE_SNAPSHOT=1 npm test
        if (!fs.existsSync(expectedFilePath) || process.env.UPDATE_SNAPSHOT) {
          fs.writeFileSync(expectedFilePath, JSON.stringify(actual, null, 4));
          this.skip(); // skip when updating snapshots - Mocha's function
          return;
        }
        // compare input and output
        const expected = JSON.parse(fs.readFileSync(expectedFilePath, "utf-8"));
        assert.deepStrictEqual(
          actual,
          expected,
          `
${fixtureDir}
${JSON.stringify(actual)}
`
        );
      });
    });
});

Setup snapshot input file

Create each test case directory to fixturesDir and put input.json as input and output.json as output into the test case directory.

├── snapshot-test.js
└── snapshots
    ├── TEST_CASE_NAME_1
    │   ├── input.json
    │   └── output.json
    └── TEST_CASE_NAME_2
        ├── input.json
        └── output.json

Create output.json(snapshot) from input.json

Snapshot testing create output file(snapshot) from input file(input.json).
It is advantage to use snapshot testing.

Run the test code with UPDATE_SNAPSHOT=1 enviroment variable and then create output.json into each test case directory.

UPDATE_SNAPSHOT=1 npm test

If You have checked the snapshot file(output.json) and it is valid, commit the snapshot file.

Next, You can check the snapshot via Running npm test:

npm test 

Conclustion

I have used the above snapshot testing pattern.
Snapshot testing is easy to increase test case by putting input case .

Examples:

Top comments (0)