Git Product home page Git Product logo

mocha-chai-jest-snapshot's Introduction

🍵mocha-chai-jest-snapshot📷

Travis (.org) npm MIT

NPM

provides snapshot testing like jest

Features

  • ✅ Simple to use
  • ✅ Output the same snapshot file as jest
  • ✅ Output the same snapshot summary as jest
  • ✅ Detect obsolete snapshots
  • ✅ Support custom serializer
  • ✅ Support typescript

Usage

npm i -D mocha-chai-jest-snapshot

then add it to the test setup:

// e.g. setup.js (mocha --file setup.js)
const chai = require("chai");
const { jestSnapshotPlugin } = require("mocha-chai-jest-snapshot");

chai.use(jestSnapshotPlugin());

enjoy.

const { expect } = require("chai");
it("foo", function () {
  expect({ foo: "bar" }).toMatchSnapshot();
});
> [email protected] test /mnt/x/chai-snapshot
> npx mocha --file setup.js -r ts-node/register test/**/*.ts


  ✓ foo

Snapshot Summary
 › 1 snapshot written from 1 test suite.

  1 passing (9ms)
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`foo 1`] = `
Object {
  "foo": "bar",
}
`;

update snapshots

# set envoriment
UPDATE_SNAPSHOT=1 mocha ...
# or add command line argument
mocha ... --update

report at the end

npx mocha ... --reporter mocha-chai-jest-snapshot/reporters/spec

with options

jest options (setup)

const chai = require("chai");
const { jestSnapshotPlugin } = require("mocha-chai-jest-snapshot");

chai.use(
  jestSnapshotPlugin({
    rootDir: "../",
    snapshotResolver: "<rootDir>/jest/snapshotResolver",
    snapshotSerializers: ["jest-serializer-vue"],
  })
);

jest options (package.json)

{
  "jest": {
    "rootDir": "../",
    "snapshotResolver": "<rootDir>/jest/snapshotResolver",
    "snapshotSerializers": ["jest-serializer-vue"]
  }
}

jest options (jest.config.js)

module.exports = {
  rootDir: "../",
  snapshotResolver: "<rootDir>/jest/snapshotResolver",
  snapshotSerializers: ["jest-serializer-vue"],
};

custom serializer

const chai = require("chai");
const {
  jestSnapshotPlugin,
  addSerializer,
} = require("mocha-chai-jest-snapshot");
const customSerializer = require("...");

chai.use(jestSnapshotPlugin());
addSerializer(customSerializer);

or

const { expect } = require("chai");
const customSerializer = require("...");

expect.addSnapshotSerializer(customSerializer);

mocha-chai-jest-snapshot's People

Contributors

mochiya98 avatar

Stargazers

Pablo Palacios avatar Sukka avatar Sepehr Laal avatar Chris avatar  avatar Konstantin Vyatkin avatar Sam Loibl avatar Jinyang Liu avatar Jdes avatar sam bacha avatar Natan Zalkin avatar Ian Kerins avatar Ankit Gupta avatar Cheng Liu avatar Jiri Spac avatar  avatar Julien Karst  avatar Paul Razvan Berg avatar Caleb Boyd avatar Jason Kurian avatar Siddharth VP avatar Vladimír Gorej avatar Miro Yovchev avatar Julian Rüth avatar laden avatar Yaraslau Byshyk avatar Bohdan Ganicky avatar Christian Hartinger avatar

Watchers

James Cloos avatar  avatar

mocha-chai-jest-snapshot's Issues

Configuration `rootDir` Appears Ignored?

For the life of me, I cannot get the plugin to respect the rootDir configuration. I've tried passing it in via:

# In Test
chai.use(jestSnapshotPlugin({ rootDir: '/absolute/path/to/directory' })

chai.use(jestSnapshotPlugin({ rootDir: '../relative/path/to/directory' })

# In <PROJECT_ROOT>/jest.config.js
module.exports = {
  rootDir: '/absolute/path/to/directory',
};

# In <PROJECT_ROOT>/package.json
{
  "jest": {
    "rootDir": "/absolute/path/to/directory"
  }
}

For whatever reason, the resulting structure looks like:

tests/
  __snapshots__/
  test.spec.ts

Whereas, I would prefer it to be something like:

snapshots/
tests/
  test.spec.ts

Great work on this library!

Just wanted to say, that you did a remarkable work on this library. Thank you, it saved me a lot of time implementing it myself!

expected 'Array [\n "attaching eventData",\n …' to equal ''

Thank you for this module. Its really great.

I am having an issue running this module in Github Actions. When I run it on my local computer it works fine, but in Github Actions I get this

expected 'Array [\n  "attaching eventData",\n  …' to equal ''

It seems that the actual is correct but the expected is a blank string.

Any ideas what I could try to help me out?

Cannot find name 'SnapshotStateOptions'

Getting this error when running tsc, with "skipLibCheck": false

node_modules/mocha-chai-jest-snapshot/dist/utils/jest-test-result-helper.d.ts:14:58 - error TS2304: Cannot find name 'SnapshotStateOptions'.

14 export declare const makeEmptySnapshotSummary: (options: SnapshotStateOptions) => SnapshotSummary;
                                                            ~~~~~~~~~~~~~~~~~~~~


Found 1 error in node_modules/mocha-chai-jest-snapshot/dist/utils/jest-test-result-helper.d.ts:14

cannot find globals 'before' and 'after'

Could not get this to work; it gives the error ReferenceError: before is not defined.

It traces back to these lines (in the built version)

    return function (chai, utils) {
        before(() => __awaiter(this, void 0, void 0, function* () {
            _manager.snapshotResolver = yield (0, jest_snapshot_1.buildSnapshotResolver)(Object.assign({ transform: [] }, config));
        }));
        beforeEach(function () {
            if (this.currentTest)
                _manager.setContext(this.currentTest);
        });
        after(function () {
            _manager.saveSnap();
            if (!_reporterAttached)
                _manager.report();
        });

Those don't seem to be globals delivered by Jest.

My jest setupFilesAfterEnv.js:

import Chai                             from 'chai'
import ChaiArrays                       from 'chai-arrays'
import ChaiAsPromised                   from 'chai-as-promised'
import ChaiEach                         from 'chai-each'
import Sinon                            from 'sinon'
import ChaiSinon                        from 'sinon-chai'
import * as SnapshotPlugin              from 'mocha-chai-jest-snapshot'

const { jestSnapshotPlugin } = SnapshotPlugin

Chai.use(ChaiArrays)
Chai.use(ChaiEach)
Chai.use(ChaiSinon)
Chai.use(SnapshotPlugin.jestSnapshotPlugin())
Chai.use(ChaiAsPromised) // must be last

global.sinon  = Sinon
global.expect = Chai.expect

Error.stackTraceLimit = 50

and jest.config.cjs:

// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

module.exports = {
  // Run tests from one or more projects
  projects: [
    {
      displayName: "tests",
      // A list of paths to modules that run some code to configure or set up the testing framework before each test
      setupFilesAfterEnv:       ['./tests/setupFilesAfterEnv.js'],
      testMatch:                ["<rootDir>/tests/**/*.test.[tj]s?(x)"],
      testPathIgnorePatterns:   ["tests\/store", "tests\/.*\/.*Store.*"],
    },
    {
      displayName: "dbtests",
      // A list of paths to modules that run some code to configure or set up the testing framework before each test
      setupFilesAfterEnv:       ['./tests/setupFilesAfterEnv.js'],
      testMatch:                ["<rootDir>/tests/store/*.test.[tj]s?(x)", "<rootDir>/tests/*/.*Store*.test.[tj]s?(x)"],
    },
    // {
    //   displayName: "lint",
    //   runner:      "jest-runner-eslint",
    //   testMatch:   ["<rootDir>/{src,tests}/**/*.{js,ts}"],
    // },
  ],
  //
  // A list of paths to directories that Jest should use to search for files in
  roots: [
    'tests',
    // 'built',
  ],

  // The glob patterns Jest uses to detect test files
  testMatch: [
    "**/tests/**/*.test.[tj]s?(x)",
  ],

  // A list of paths to modules that run some code to configure or set up the testing framework before each test
  setupFilesAfterEnv: ['./tests/setupFilesAfterEnv.js'],

  // The test environment that will be used for testing
  testEnvironment: "node",

  // Indicates whether each individual test should be reported during the run
  verbose: true,

  // The maximum amount of workers used to run your tests. Can be specified as % or a number.
  // E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number.
  //      maxWorkers: 2 will use a maximum of 2 workers.
  maxWorkers: "30%",
}

snapshots get updated every time

Hi! I'm running into the problem that the snapshots get updated on every run, even if UPDATE_SNAPSHOT is set to false. I have a very basic setup with typescript, here is the setup.ts file:

import * as chai from 'chai';
import { jestSnapshotPlugin } from 'mocha-chai-jest-snapshot';

chai.use(jestSnapshotPlugin());

And every time I'm running this command the snapshot gets updated:

npx mocha --file test/setup.ts -r ts-node/register test/**/*.test.ts

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.