DEV Community

azu
azu

Posted on

1 1

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:

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️