GithubHelp home page GithubHelp logo

satya164 / jest-file-snapshot Goto Github PK

View Code? Open in Web Editor NEW
40.0 3.0 14.0 2.34 MB

Jest matcher to write snapshots to a separate file instead of the default snapshot file used by Jest

JavaScript 100.00%
jest snapshot-testing testing hacktoberfest

jest-file-snapshot's Introduction

jest-file-snapshot

Build Status Code Coverage MIT License Version

Jest matcher to write snapshots to a separate file instead of the default snapshot file used by Jest. Writing a snapshot to a separate file means you have proper syntax highlighting in the output file, and better readability without those pesky escape characters. It's also useful if you have binary content.

Installation

npm install --save-dev jest-file-snapshot

or

yarn add --dev jest-file-snapshot

Usage

Extend Jest's expect:

import { toMatchFile } from 'jest-file-snapshot';

expect.extend({ toMatchFile });

Then use it in your tests:

it('matches content of file on disk', () => {
  expect(content).toMatchFile();
});

The content passed can be of type string or a Buffer. The comparison be done using Buffer.equals() instead of === if a Buffer is passed.

The matcher takes two optional arguments:

  • filepath: path to the file whose content should be matched, e.g. expect(content).toMatchFile(path.join(__dirname, 'output.md'))
  • options: additional options object for the matcher, with following properties:
    • diff: options for jest-diff
    • fileExtension: optional file extension to use for the snapshot file.

You should also exclude the output files from Jest's watcher so that updating the snapshot doesn't re-run the tests again.

For example, by default toMatchFile uses a folder named __file_snapshots__ which you can exclude by adding the following under the jest key in package.json:

"watchPathIgnorePatterns": [
  "__file_snapshots__"
]

Credits

Contributing

Make sure your code passes the unit tests, ESLint and TypeScript. Run the following to verify:

yarn test
yarn lint
yarn typescript

To fix formatting errors, run the following:

yarn lint -- --fix

jest-file-snapshot's People

Contributors

colinking avatar dependabot[bot] avatar dylanpiercey avatar fwouts avatar jiangweixian avatar milahu avatar nokome avatar satya164 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jest-file-snapshot's Issues

Component snapshot support

We've been looking for a tool like this. However, it does not work with our existing tools.

In our project we use enzyme's shallow, mount.

Currently we have the following:

const wrapper = shallow(<Component {...props} />);
expect(wrapper.get(0)).toMatchSnapshot();

Migrating to this tool by simply replacing the matcher does not work as expected

const wrapper = shallow(<Component {...props} />);
expect(wrapper.get(0)).toMatchFile();

Output in the snapshot file: [object Object]

Tested with react-test-renderer too and also produces [object Object].

Tried with .html() of enzyme

const wrapper = shallow(<Component {...props} />);
expect(wrapper.html()).toMatchFile();

html is produced, but in one-liner, without formatting :(

<div class="some class"><span></span><div><div><h1>Details</h1></div></div></span></div>

It'd be great if this tool has the proper support for component snapshotting :)

assert seems backwards

The output seems reversed...the "expected" value in the diff is actually the "received", e.g. the incoming change. Just me or a real thing?

add option fileExtension

let me set the file extension of the snapshot file
to enable syntax highlighting in the github blob API

expect(output).toMatchFile(undefined, {
  fileExtension: ".tsx",
});

currently, the snapshot files have no extension

src/__tests__/__file_snapshots__/some-name-0
src/__tests__/__file_snapshots__/another-name-0

Snapshot file is not removed

describe('desc A', () => {
  it('should produce A', () => {
    expect('A').toMatchFile();
  });
});

describe('desc B', () => {
  it('should produce B', () => {
    expect('B').toMatchFile();
  });
});

Will produce two snapshot files in the __file_snapshots__

When one of the tests is removed the snapshot file of the removed test still exists in the folder. Expected to be removed.

Cannot find name 'CustomMatcherResult'

Getting the following error when trying to build a project that references v0.5.0

node_modules/jest-file-snapshot/index.d.ts:9:6 - error TS2304: Cannot find name 'CustomMatcherResult'.

9 ) => CustomMatcherResult;
       ~~~~~~~~~~~~~~~~~~~


Found 1 error.

TypeError on 0.6 update

Hello,

after updating to version 0.6.0 I get a TypeError when I have diverging snapshots.

  TypeError: diff is not a function

    164 |   });
    165 |
  > 166 |   expect(code).toMatchFile();
        |                ^
    167 | });
    168 |

    at Object.toMatchFile (node_modules/jest-file-snapshot/index.js:118:24)
    at __EXTERNAL_MATCHER_TRAP__ (node_modules/expect/build/index.js:325:30)
    at Object.throwingMatcher [as toMatchFile] (node_modules/expect/build/index.js:326:15)
    at toMatchFile (test/index.spec.js:166:16)

Env:
Node.js 22
npm 10.7.0
Jest 29.7.0

Treat TypedArray as Buffer

Now if I passed in a Uint8Array it will give me a confusing error:

Comparing two different types of values. Expected string but received object.

Allow character-by-character diffs

jest-diff has implemented two modes of comparing multiline strings:

  • diffLinesUnified for comparing inputs line-by-line - used by diff, which in turn is used by this package;
  • diffStringsUnified, for comparing character-by-character, which is slower but also shows changed substrings within the lines with inverse foreground and background - used by standard equality matchers like toBe.

I have big snapshots with long lines and would prefer to see where exactly in line is the difference.
I suggest changing the diff call to diffStringsUnified or maybe make it configurable if performance is a concern, and set some sensible defaults.

This is for example what jest-diff recommends:

If the input strings can have arbitrary length, we recommend that the calling code set a limit, beyond which splits the strings, and then calls diffLinesUnified instead. For example, Jest falls back to line-by-line comparison if either string has length greater than 20K characters.

Add lock file

Thanks for putting this repo together! Ran into a similar issue with a project I'm working on. Would love to see something similar in scope merged into jest ๐Ÿ˜„

Any interest in adding a package-lock.json or adding a yarn.lock file?

Snapshot behavior for objects different than built in jest snapshot

For anyone coming across this this library, be aware that it only seems to support JSON data. Objects/classes will serialize to [Object object] and that's what your snapshots will contain.

I've been able to combine this with json-cycle to create useful snapshots, that were also much much faster than jest's default snapshotting implementation.

For bigger objects, it would take upwards of 5 seconds to generate and analyze a snapshot using jest .toMatchSnapshot() while with this library and json-cycle, the time has been cut to a few miliseconds.

Implementation example:

import { toMatchFile } from 'jest-file-snapshot';
import * as js from 'json-cycle';
import * as path from 'path';

expect.extend({ toMatchFile });

describe('some app feature', () => {
  describe('snapshot tests', () => {
    it('matches previous snaps of xyz', async () => {
      ...
      const data = ...;
      expect(JSON.stringify(js.decycle(data), null, 2)).toMatchFile(
        path.join(__dirname, '__file_snapshots__', 'snap-xyz.json')
      );

It would be nice if this was entirely built in. Issue #9 is also related.

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.