Git Product home page Git Product logo

snapshot-diff's Introduction

snapshot-diff

Greenkeeper badge npm version

Diffing snapshot utility for Jest. Takes two values, and return their difference as a string, ready to be snapshotted with toMatchSnapshot(). Especially helpful when testing the difference between different React component states.

Installation

yarn add --dev snapshot-diff

Usage

With default jest matcher

const snapshotDiff = require('snapshot-diff');

test('snapshot difference between 2 strings', () => {
  expect(snapshotDiff(a, b)).toMatchSnapshot();
});

const React = require('react');
const Component = require('./Component');

test('snapshot difference between 2 React components state', () => {
  expect(
    snapshotDiff(<Component test="say" />, <Component test="my name" />)
  ).toMatchSnapshot();
});

With custom matcher

const { toMatchDiffSnapshot } = require('snapshot-diff');

expect.extend({ toMatchDiffSnapshot });

test('snapshot difference between 2 strings', () => {
  expect(a).toMatchDiffSnapshot(b);
});

const React = require('react');
const Component = require('./Component');

test('snapshot difference between 2 React components state', () => {
  expect(<Component test="say" />).toMatchDiffSnapshot(
    <Component test="my name" />
  );
});

... alternatively import it once, for instance in your tests setup file:

require('snapshot-diff/extend-expect');

Produced snapshot:

exports[`snapshot difference between 2 strings 1`] = `
"- First value
+ Second value


-  abcx
+  abcy
   "
`;

exports[`snapshot difference between 2 React components state 1`] = `
"- <Component test=\\"say\\" />
+ <Component test=\\"my name\\" />

@@ -27,11 +27,11 @@
   <span />
   <span />
   <span />
   <span />
   <span>
-    say
+    my name
   </span>
   <span />
   <span />
   <span />
   <span />"
`;

Custom serializers

By default, snapshot-diff uses a built in React serializer based on react-test-renderer. The serializers used can be set by calling setSerializers with an array of serializers to use. The order of serializers in this array may be important to you as serializers are tested in order until a match is found.

setSerializers can be used to add new serializers for unsupported data types, or to set a different serializer for React components. If you want to keep the default React serializer in place, don't forget to add the default serializers to your list of serializers!

Adding a new custom serializer

const snapshotDiff = require('snapshot-diff');
const myCustomSerializer = require('./my-custom-serializer');

snapshotDiff.setSerializers([
  ...snapshotDiff.defaultSerializers, // use default React serializer - add this if you want to serialise React components!
  myCustomSerializer
]);

Serializing React components with a different serializer

You can replace the default React serializer by omitting it from the serializer list. The following uses enzymes to-json serializer instead:

const snapshotDiff = require('snapshot-diff');
const enzymeToJson = require('enzyme-to-json/serializer');
const myCustomSerializer = require('./my-custom-serializer');

snapshotDiff.setSerializers([
  enzymeToJson, // using enzymes serializer instead
  myCustomSerializer
]);

Snapshot serializer

By default Jest adds extra quotes around strings so it makes diff snapshots of objects too noisy. To fix this – snapshot-diff comes with custom serializer, which you can add directly in your tests or in setupFiles script:

const snapshotDiff = require('snapshot-diff');

expect.addSnapshotSerializer(snapshotDiff.getSnapshotDiffSerializer());

test('snapshot difference between 2 objects', () => {
  expect(snapshotDiff({ foo: 'bar' }, { foo: 'baz' })).toMatchSnapshot();
});

...or add it globally to your jest config:

// jest.config.js
module.exports = {
  snapshotSerializers: [
    require.resolve('snapshot-diff/serializer.js'),
  ],
};

API

type Options = {
  expand?: boolean,
  colors?: boolean,
  contextLines?: number
};

// default export
snapshotDiff(valueA: any, valueB: any, options?: Options) => string
// custom matcher
expect(valueA: any).toMatchDiffSnapshot(valueB: any, options?: Options, testName?: string) => void

Options

  • expand: boolean (default: false) – expand the diff, so the whole information is preserved
  • colors: boolean (default: false) – preserve color information from Jest diff
  • contextLines: number (default: 5) - number of context lines to be shown at the beginning and at the end of a snapshot
  • stablePatchmarks: boolean (default: false) - prevent line number patch marks from appearing in diffs. This can be helpful when diffs are breaking only because of the patch marks. Changes @@ -1,1 +1,2 @@ to @@ --- --- @@.
  • aAnnotation: string (default: 'First Value') - the annotation indicating from which serialization the - lines are
  • bAnnotation: string (default: 'Second Value') - the annotation indicating from which serialization the + lines are

Project is MIT-licensed. Pull Requests welcome!

snapshot-diff's People

Contributors

alistairjcbrown avatar asapach avatar avocadowastaken avatar coryhouse avatar dependabot-preview[bot] avatar dependabot[bot] avatar dsifford avatar ericbiewener avatar ferrannp avatar greenkeeper[bot] avatar kpsroka avatar maraisr avatar orta avatar renovate[bot] avatar rrufus avatar simenb avatar thymikee 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

snapshot-diff's Issues

An in-range update of eslint is breaking the build 🚨

The devDependency eslint was updated from 6.6.0 to 6.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v6.7.0
  • 312a88f New: Add grouped-accessor-pairs rule (fixes #12277) (#12331) (Milos Djermanovic)
  • 5c68f5f Update: Add 'lexicalBindings' to no-implicit-globals and change messages (#11996) (Milos Djermanovic)
  • 6eaad96 New: Add suggestions API (#12384) (Will Douglas)
  • b336fbe Fix: indent rule with JSX spread props (#12581) (Nathan Woltman)
  • 97c745d Update: Report assignment expression location in no-cond-assign (#12465) (Milos Djermanovic)
  • 0f01f3d Update: Check member expressions with this in operator-assignment (#12495) (Milos Djermanovic)
  • 62c7038 Fix: invalid token checking in computed-property-spacing (fixes #12198) (#12533) (YeonJuan)
  • 4f8a1ee Update: Add enforceForClassMembers option to no-useless-computed-key (#12110) (ark120202)
  • 1a2eb99 New: new rule no-constructor-return (fixes #12481) (#12529) (Pig Fang)
  • ca3b2a6 New: ignorePatterns in config files (refs eslint/rfcs#22) (#12274) (Toru Nagashima)
  • 60204a3 Docs: Added another Textmate 2 bundle. (#12580) (Ryan Fitzer)
  • 62623f9 Fix: preserve whitespace in multiline-comment-style (fixes #12312) (#12316) (Kai Cataldo)
  • 17a8849 New: Add no-dupe-else-if rule (fixes #12469) (#12504) (Milos Djermanovic)
  • 41a78fd Update: improve location for semi and comma-dangle (#12380) (Chiawen Chen)
  • 0a480f8 Docs: Change "Code Conventions" link in pull-requests.md (#12401) (Denis Sikuler)
  • fed20bb Fix: require-await crash on global await (#12571) (Brad Zacher)
  • b8030fc Update: deprecate personal config (fixes #11914, refs eslint/rfcs#32) (#12426) (Toru Nagashima)
  • 40c8c32 Fix: improve report location for object-curly-spacing (#12563) (Milos Djermanovic)
  • 1110045 Fix: ignore marker-only comments in spaced-comment (fixes #12036) (#12558) (Milos Djermanovic)
  • 6503cb8 Update: Fix uglified object align in key-spacing (fixes #11414) (#12472) (YeonJuan)
  • 40791af Docs: clarify ignoreDestructuring option in the camelcase rule (#12553) (Milos Djermanovic)
  • 07d398d Chore: Add GitHub organization to Sponsor button (#12562) (Brandon Mills)
  • a477707 Chore: Format style guide links so they can be clicked (#12189) (Ivan V)
  • 0f7edef Update: add react plugin config for eslint init (#12446) (Ibrahim Rouis)
  • 448ff1e Update: Report '\08' and '\09' in no-octal-escape (fixes #12080) (#12526) (Milos Djermanovic)
  • 45aa6a3 New: Add no-setter-return rule (fixes #12285) (#12346) (Milos Djermanovic)
  • 0afb518 Fix: invalid autofix in function-call-argument-newline (fixes #12454) (#12539) (YeonJuan)
  • 90305e0 Update: Depcrecate isSpaceBetweenTokens() (#12519) (Kai Cataldo)
  • 41b1e43 New: add option for camelcase (fixes #12527) (#12528) (Pig Fang)
  • f49f1e0 Upgrade: upgrade optionator to avoid license issue (fixes #11536) (#12537) (Pig Fang)
  • 0286b57 Docs: Clean up Getting Started Guide (#12544) (Nicholas C. Zakas)
  • 575a98d Chore: Add funding field to package.json (#12543) (Nicholas C. Zakas)
  • 9e29e18 Fix: sourceCode#isSpaceBetweenTokens() checks non-adjacent tokens (#12491) (Kai Cataldo)
  • 5868550 Docs: add notice about function keyword in keyword-spacing (#12524) (Pig Fang)
  • bb556d5 Fix: curly multi reports single lexical declarations (fixes #11908) (#12513) (Milos Djermanovic)
  • ac60621 Fix: unexpected autofix in prefer-const (fixes #12514) (#12521) (YeonJuan)
  • 990065e Update: curly multi-or-nest flagging semis on next line (fixes #12370) (#12378) (cherryblossom000)
  • 084a8a6 Fix: no-cond-assign with always option reports switch case clauses (#12470) (Milos Djermanovic)
  • 7e41355 Update: improve report location for space-infix-ops (#12324) (Chiawen Chen)
  • 94ff921 Update: Add capIsConstructor option to no-invalid-this (fixes #12271) (#12308) (Milos Djermanovic)
  • de65de6 New: Add prefer-exponentiation-operator rule (fixes #10482) (#12360) (Milos Djermanovic)
  • c78f4a7 Update: Allow JSX exception in no-inline-comments (fixes #11270) (#12388) (Milos Djermanovic)
  • e17fb90 New: allowAfterThisConstructor for no-underscore-dangle (fixes #11488) (#11489) (sripberger)
  • 287ca56 Build: update CI for Node.js 13 (#12496) (Toru Nagashima)
  • 98e1d50 Upgrade: globals to v12.1.0 (#12296) (Tony Brix)
  • 8ac71a3 Sponsors: Sync README with website (ESLint Jenkins)
  • 4e142ea Docs: Update README team and sponsors (ESLint Jenkins)
Commits

The new version differs by 49 commits.

  • 61848b4 6.7.0
  • 9162db9 Build: changelog update for 6.7.0
  • 312a88f New: Add grouped-accessor-pairs rule (fixes #12277) (#12331)
  • 5c68f5f Update: Add 'lexicalBindings' to no-implicit-globals and change messages (#11996)
  • 6eaad96 New: Add suggestions API (#12384)
  • b336fbe Fix: indent rule with JSX spread props (#12581)
  • 97c745d Update: Report assignment expression location in no-cond-assign (#12465)
  • 0f01f3d Update: Check member expressions with this in operator-assignment (#12495)
  • 62c7038 Fix: invalid token checking in computed-property-spacing (fixes #12198) (#12533)
  • 4f8a1ee Update: Add enforceForClassMembers option to no-useless-computed-key (#12110)
  • 1a2eb99 New: new rule no-constructor-return (fixes #12481) (#12529)
  • ca3b2a6 New: ignorePatterns in config files (refs eslint/rfcs#22) (#12274)
  • 60204a3 Docs: Added another Textmate 2 bundle. (#12580)
  • 62623f9 Fix: preserve whitespace in multiline-comment-style (fixes #12312) (#12316)
  • 17a8849 New: Add no-dupe-else-if rule (fixes #12469) (#12504)

There are 49 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.8.6 to 16.9.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for 16.9.0 (August 8, 2019)

React

  • Add <React.Profiler> API for gathering performance measurements programmatically. (@bvaughn in #15172)
  • Remove unstable_ConcurrentMode in favor of unstable_createRoot. (@acdlite in #15532)

React DOM

React DOM Server

  • Fix incorrect output for camelCase custom CSS property names. (@bedakb in #16167)

React Test Utilities and Test Renderer

Artifacts

• react: https://unpkg.com/[email protected]/umd/
• react-art: https://unpkg.com/[email protected]/umd/
• react-dom: https://unpkg.com/[email protected]/umd/
• react-is: https://unpkg.com/[email protected]/umd/
• react-test-renderer: https://unpkg.com/[email protected]/umd/
• scheduler: https://unpkg.com/[email protected]/umd/

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Jest 25 support

Jest 25 was release a week ago, are there plans to support v25?

dependencies": {
    "jest-diff": "^24.0.0",
    "jest-snapshot": "^24.0.0",
     ...
  }

@@ notation

What does this notation represent?

@@ -27,11 +27,11 @@

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/nodejs.yml
  • actions/checkout v3
  • actions/setup-node v3
npm
package.json
  • jest-diff ^29.0.0
  • jest-snapshot ^29.0.0
  • pretty-format ^29.0.0
  • @babel/cli ^7.7.0
  • @babel/core ^7.7.2
  • @babel/preset-env ^7.7.1
  • @babel/preset-flow ^7.0.0
  • @babel/preset-react ^7.7.0
  • @callstack/eslint-config ^13.0.0
  • enzyme ^3.10.0
  • enzyme-adapter-react-16 ^1.14.0
  • enzyme-to-json ^3.4.0
  • eslint ^8.0.0
  • flow-bin ^0.129.0
  • jest ^29.0.0
  • react ^16.13.1
  • react-dom 16.14.0
  • react-test-renderer ^16.13.1
  • jest >=16
  • node >=14

  • Check this box to trigger a request for Renovate to run again on this repository

`toMatchDiffSnapshot()` exposes undefined instead of diffs

toMatchDiffSnapshot() extend the global object as described in README.

import { toMatchDiffSnapshot } from 'snapshot-diff';

global.expect.extend({ toMatchDiffSnapshot });

So, in this case it provides me this snap:
image

I've made temporary solution by just exporting shapshotDiff itself and extending the global object in this way:

global.expect.extend({
  toMatchDiffSnapshot(lhs, rhs) {
    const diffs = shapshotDiff(lhs, rhs);
    return toMatchSnapshot.call(this, diffs);
  },
});

And response is:
image

Remove unnecessary boilerplate from snapshots

I'm using snapshot-diff with the custom serializer:

  "jest": {
    "snapshotSerializers": [
      "snapshot-diff/serializer.js"
    ]
}
expect(initialTemplate).toMatchDiffSnapshot(result, {contextLines: 3});

And I'm getting snapshot output like this:

exports[`Template actions setPageTitle should set the meta.title belonging to the page 1`] = `
Snapshot Diff:
- First value
+ Second value

@@ -16,7 +16,7 @@
    "pages": Object {
      "test-01": Object {
        "meta": Object {
-         "title": "Untitled",
+         "title": "Page 1",
        },
      },
      ...
`;

It's a little annoying because these lines are redundant, the test isn't going to cease to be a snapshot diff and I don't need information about how diffs work embedded inside every single snapshot.

Snapshot Diff:
- First value
+ Second value

diff output includes many unnecessary lines

Below is an output of my component.
The first block is my intention on this test case.
And I do not want the second block including so many plus.

exports[`add active class name on current page menu 1`] = `
"Snapshot Diff:
- <CategoryMenu categoryNew={{}} currentPageCategory={0} dispatch={[Function dispatch]} />
+ <CategoryMenu categoryNew={{}} currentPageCategory={11} dispatch={[Function dispatch]} />

@@ -45,11 +45,11 @@
              src=\\"/static/cate_toon.png\\"
            />
          </a>
        </li>
        <li
-         className=\\"jsx-2668475347 mainItem \\"
+         className=\\"jsx-2668475347 mainItem active \\"
          data-category={11}
          onClick={[Function anonymous]}
        >
          <a
            className=\\"jsx-2668475347\\"
@@ -110,6 +110,87 @@
            />
          </a>
        </li>
      </ul>
    </div>
+   <ul
+     className=\\"jsx-691579916 subCateNav subCateNav_pc \\"
+   >
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=1100\\"
+         onClick={[Function bound linkClicked]}
+       >
+         asdf
+       </a>
+     </li>
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=1101\\"
+         onClick={[Function bound linkClicked]}
+       >
+         asdf
+       </a>
+     </li>
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=86\\"
+         onClick={[Function bound linkClicked]}
+       >
+         asdf
+       </a>
+     </li>
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=120\\"
+         onClick={[Function bound linkClicked]}
+       >
+         adsf
+       </a>
+     </li>
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=89\\"
+         onClick={[Function bound linkClicked]}
+       >
+         asdf
+       </a>
+     </li>
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=117\\"
+         onClick={[Function bound linkClicked]}
+       >
+         asdf
+       </a>
+     </li>
+     <li
+       className=\\"jsx-1102196228 subItem subItem_pc \\"
+     >
+       <a
+         className=\\"jsx-1102196228\\"
+         href=\\"/v2/main?categoryUid=11&subCategoryUid=87\\"
+         onClick={[Function bound linkClicked]}
+       >
+         asdf
+       </a>
+     </li>
+   </ul>
  </div>"
`;

It would be nice if I can select output area by using options like targetBlocks or targetLines.

snapshotDiff(
  <CategoryMenu
    categoryNew={{}}
    currentPageCategory={Category.None}
    dispatch={dispatch}
  />,
  <CategoryMenu
    categoryNew={{}}
    currentPageCategory={Category.Novel}
    dispatch={dispatch}
  />,
  options: {
    targetBlocks: [1],
  }
);

Release the next version

The published 0.2.2 version relies on jest test releases:

//package.json
...
"jest-diff": "test",
"jest-snapshot": "test"

It was recently fixed in #21, could you please release a new version to avoid loading beta dependencies - at the moment you have to adjust dependencies manually each time when you add/update a package.

`0.8.0` has ansi escape codes

image

I don't think we want this?

Makes for a very weird diff when seeing it in a terminal which respects these characters
image

Consider calling rendering with current jest.config

Currently, the configured jest.config isn't considered when creating snapshots. Therefore, e.g. styled-component serializer is ignored, if configured. Issue #30 is similar, but doesn't consider existing configurations.

Jest mock names not honoured in resulting snapshot

I've encountered an issue where taking a snapshot diff doesn't maintain a mock functions name. I've outlined a simplistic example to reproduce below:

// component.js

import React from 'react';
import PropTypes from 'prop-types';

const Component = ({ text, onClick }) =>
  <button onClick={onClick}>{text}</button>;

Component.propTypes = {
  onClick: PropTypes.func,
  text: PropTypes.string
};

Component.defaultProps = {
  text: 'Hello world!'
};

export default Component;
// component.spec.js

import React from 'react';
import renderer from 'react-test-renderer';
import Component from './component';

describe('Component', () => {
  it('renders correctly', () => {
    expect(renderer.create(
      <Component onClick={jest.fn().mockName('onClick')} />
    )).toMatchSnapshot();
  });

  it('accepts text and click functionality', () => {
    expect(
      renderer.create(
        <Component />
      )
    ).toMatchDiffSnapshot(
      renderer.create(
        <Component
          onClick={jest.fn().mockName('onClick')}
          text='Foo bar'
        />
      )
    );
  })
});
// component.spec.js.snap

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Component accepts text and click functionality 1`] = `
"Snapshot Diff:
- First value
+ Second value

- <button>
-   Hello world!
+ <button
+   onClick={[Function mockConstructor]}
+ >
+   Foo bar
  </button>"
`;

exports[`Component renders correctly 1`] = `
<button
  onClick={[MockFunction onClick]}
>
  Hello world!
</button>
`;

The above example shows that a standard snapshot honours the mock name, but the resulting diff does not. I'm unsure if this is a setup problem on my part but my assumption is that it's not; my understanding is that snapshot-diff uses react-test-renderer under the hood by default, so I'd have expected the mock name to have been honoured.

An in-range update of jest2 is breaking the build 🚨

There have been updates to the jest2 monorepo:

    • The dependency pretty-format was updated from 23.5.0 to 23.6.0.
  • The dependency jest-snapshot was updated from 23.5.0 to 23.6.0.
  • The dependency jest-diff was updated from 23.5.0 to 23.6.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the jest2 group definition.

jest2 is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

snapshotDiff between two single line strings output null

Code:

expect(snapshotDiff("foo", "bar")).toMatchSnapshot();

Result:

Received value
    Snapshot Diff:
    null

It seems adding a new line to the end of both arguments results in a valid snapshot diff.

Code

expect(snapshotDiff("foo" + "\n", "bar" + "\n")).toMatchSnapshot();

Result

Received value
    Snapshot Diff:
    - First value
    + Second value

    - foo
    + bar

Doesn't work with jest v23

Updating to jest 23 result in all diff snapshots to disappear. They are replaced with this:

exports[`undefined 1`] = `undefined`;

An in-range update of babel7 is breaking the build 🚨

There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.4.4 to 7.5.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the babel7 group definition.

babel7 is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Set the default options globally

Is there any way to set custom default values globally (where it can be set in a beforeAll or in the jest setup) so you don't need to add the options into every snapshotDiff call? (eg. Want to have 0 context lines as the default.)

Support react shallow render.

I usually write the snapshot tests using enzyme shallow render:

it('matches snapshot', () => {
  const shallowNode = shallow(<Component />).getNode();
  expect(shallowNode).toMatchSnapshot();
});

I would like to keep this approach when having diffs. However, I get fully rendered components when I do:

it('matches diff snapshot', () => {
  const firstShallowNode = shallow(<Component />).getNode();
  const secondShallowNode = shallow(<Component selected />).getNode();
  expect(firstShallowNode).toMatchDiffSnapshot(secondShallowNode)
});

That's because .getNode also returns a React Component so the diff will choose the react diff path

I'm not sure what would be the solution for this. I've modified the code to ignore the Component check statement and it works fine with diffStrings.

Support custom snapshot serializers on diff inputs

My exact use case for this involves migrating from react-test-renderer to enzyme.mount - the former is natively supported by pretty-format while the latter ships with a custom serializer.

Would it make sense for snapshot-diff to support an API similar to expect.addSnapshotSerializer? Maybe with a slightly more hygienic twist:

import snapshotDiff from "snapshotDiff";
import enzymeToJson from "enzyme-to-json/serializer";

const diff = snapshotDiff.withSerializers([enzymeToJson]);
diff(a, b); // Runs `a` and `b` through the given serializers before diffing

I'm happy to put together a PR for this over the next few days.

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

I've encountered an issue where taking a snapshot diff doesn't produce the expected output. I've outlined a simplistic example to reproduce below:

// component.js

import React from 'react';
import { View } from 'react-native';

const Component = ({withSeparator}) =>
  <>
    <View/>
    {withSeparator ? <View /> : null }
  </>

export default Component;
// component.test.js

import React from 'react';
import renderer from 'react-test-renderer';
import Component from './component';

it('should show separator, () => {
    expect(<Component />).toMatchDiffSnapshot(<Component withSeparator />);
});
// component.test.js.snap

exports[`should show separator 1`] = `
Snapshot Diff:
  Comparing two different types of values. Expected array but received object.
`;

The above error is produced by diffStrings and occured when we compare an array with an object.
In this case, the call is :

difference = diffStrings(print(valueA, identity), print(valueB, identity), ...);

// print(valueA, identity) = { type: 'View', props: {}, children: null }
// print(valueB, identity) = [ { type: 'View', props: {}, children: null },
      { type: 'View', props: {}, children: null } ]

A solution to this issue could be to wrap the object in an array.

An in-range update of eslint is breaking the build 🚨

The devDependency eslint was updated from 5.15.1 to 5.15.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v5.15.2
  • 29dbca7 Fix: implicit-arrow-linebreak adds extra characters (fixes #11268) (#11407) (Mark de Dios)
  • 5d2083f Upgrade: [email protected] (#11513) (Teddy Katz)
  • a5dae7c Fix: Empty glob pattern incorrectly expands to "/**" (#11476) (Ben Chauvette)
  • 448e8da Chore: improve crash reporting (fixes #11304) (#11463) (Alex Zherdev)
  • 0f56dc6 Chore: make config validator params more consistent (#11435) (薛定谔的猫)
  • d6c1122 Docs: Add working groups to maintainer guide (#11400) (Nicholas C. Zakas)
  • 5fdb4d3 Build: compile deps to ES5 when generating browser file (fixes #11504) (#11505) (Teddy Katz)
  • 06fa165 Build: update CI testing configuration (#11500) (Reece Dunham)
  • 956e883 Docs: Fix example in no-restricted-modules docs (#11454) (Paul O’Shannessy)
  • 2c7431d Docs: fix json schema example dead link (#11498) (kazuya kawaguchi)
  • e7266c2 Docs: Fix invalid JSON in "Specifying Parser Options" (#11492) (Mihira Jayasekera)
  • 6693161 Sponsors: Sync README with website (ESLint Jenkins)
  • 62fee4a Chore: eslint-config-eslint enable comma-dangle functions: "never" (#11434) (薛定谔的猫)
  • 34a5382 Build: copy bundled espree to website directory (#11478) (Pig Fang)
  • f078f9a Chore: use "file:" dependencies for internal rules/config (#11465) (Teddy Katz)
  • 0756128 Docs: Add visualstudio to formatter list (#11480) (Patrick Eriksson)
  • 44de9d7 Docs: Fix typo in func-name-matching rule docs (#11484) (Iulian Onofrei)
Commits

The new version differs by 19 commits.

  • f354770 5.15.2
  • cada7a1 Build: changelog update for 5.15.2
  • 29dbca7 Fix: implicit-arrow-linebreak adds extra characters (fixes #11268) (#11407)
  • 5d2083f Upgrade: [email protected] (#11513)
  • a5dae7c Fix: Empty glob pattern incorrectly expands to "/**" (#11476)
  • 448e8da Chore: improve crash reporting (fixes #11304) (#11463)
  • 0f56dc6 Chore: make config validator params more consistent (#11435)
  • d6c1122 Docs: Add working groups to maintainer guide (#11400)
  • 5fdb4d3 Build: compile deps to ES5 when generating browser file (fixes #11504) (#11505)
  • 06fa165 Build: update CI testing configuration (#11500)
  • 956e883 Docs: Fix example in no-restricted-modules docs (#11454)
  • 2c7431d Docs: fix json schema example dead link (#11498)
  • e7266c2 Docs: Fix invalid JSON in "Specifying Parser Options" (#11492)
  • 6693161 Sponsors: Sync README with website
  • 62fee4a Chore: eslint-config-eslint enable comma-dangle functions: "never" (#11434)

There are 19 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Option to add ```diff block to the snapshot diff

It would be nice to add the ability to add diff into the code block like:

```diff

Then I would be able to see snapshots diff in github directly with colors like:

@@ -26,4 +26,9 @@
-      Object {
-        "paddingHorizontal": 24,
-        "paddingVertical": 8,
-      }
+      Array [
+        Object {
+          "paddingHorizontal": 24,
+          "paddingVertical": 8,
+        },
+        Object {
+          "backgroundColor": "#B2DFDB",
+        },
+      ]
@@ -58,0 +63,7 @@
+    <Text
+      accessible={true}
+      allowFontScaling={true}
+      ellipsizeMode="tail"
+    >
+      Useful description goes here.
+    </Text>
`;

TypeScript error when passing enzymeToJson to setSerializers

Hello, here is my setup code:

test-setup.ts

import * as snapshotDiff from 'snapshot-diff';

// This is the same function exposed in `enzyme-to-json/serializer' as per README
import { createSerializer } from 'enzyme-to-json'; 

const enzymeToJsonSerializer = createSerializer();
snapshotDiff.setSerializers([enzymeToJsonSerializer]);

This produces the following error:

error TS2741: Property 'diffOptions' is missing in type 'JestSerializer' but required in type 'Serializer'.

This seems like a mismatch between the Serializer type in this repository and the JestSerializer type from enzyme-to-json.

My understanding is that a serializer should only have two required properties (print and test) so perhaps diffOptions needs to be optional? Note that it appears the source code expects it to be optional already

If I try to make that change I get:

 error TS2322: Type 'JestSerializer' is not assignable to type 'Serializer'.
  Types of property 'print' are incompatible.
    Type '(CommonWrapper: CommonWrapper<{}, {}, Component<{}, {}, any>>, serializer: JestSerializer) => Json' is not assignable to type '(value: any, _serializer?: Function | undefined) => string'.
      Types of parameters 'serializer' and '_serializer' are incompatible.
        Type 'Function | undefined' is not assignable to type 'JestSerializer'.
          Type 'undefined' is not assignable to type 'JestSerializer'.

Let me know if I can provide further debugging help, thanks

Add ability to suppress line numbers from diff

When diffing component state, I get something that looks like this because only this single line changed in the dom:

@@ -89,1 +89,1 @@
-                   class="MuiSelect-root-180 bold red-500"
+                   class="MuiSelect-root-230 bold tp-green-500"

That's great! But if I modify an unrelated part of the component that results in additional lines of DOM before the class name change that I'm actually concerned about, the diff breaks because the @@ -89,1 +89,1 @@ line number may have become @@ -93,1 +93,1 @@.

Can we add an option to suppress the line numbers?

Typescript support

Hello,

Is there anyway to add some support for typescript? At the moment I need to add @ts-ignore so typescript does not complain about toMatchDiffSnapshot not existing.

Example:

// @ts-ignore
expect(subject.toJSON()).toMatchDiffSnapshot(
      subject2.toJSON()
);

Exact typescript error:
Property 'toMatchDiffSnapshot' does not exist on type 'Matchers<ReactTestRendererJSON | null

Add option for adding related Component separators

We want to give the option to show snapshot diffs like:

@@ -27,11 +27,11 @@
   <span />
   <span />
   <span />
   <span />
   <span>
>>>
>>> <ComponentA test="say" /> 
>>>
-    say
<<<
<<< <ComponentB test="my name" />
<<<
+    my name
<<<
   <span />
   <span />
   <span />
<<<
<<< <ComponentB test="my name" />
<<<
+   <span />
+   <span />
<<<"
`;

Exact syntax to be discussed.

More jest integration

First of all I would like to thank you for your work!
It allowed me to decreased snapshot file size from 10k lines to 1.3k!

Add custom matcher

e.g. https://github.com/americanexpress/jest-image-snapshot#usage
See https://facebook.github.io/jest/docs/expect.html#expectextendmatchers
Usage:

expect(nextState).toMatchDiffSnapshot(prevState, { contextLines: 2 })

Add snapshot serializer based on input type

e.g. https://github.com/prettier/prettier/blob/master/tests_config/raw-serializer.js

Current output for object diffs is too noisy, so I had do implement custom serializer in my project, and now output changed from:

 Object {
   \\"bail\\": false,
   \\"context\\": \\".\\",
   \\"devServer\\": Object {
     \\"disableHostCheck\\": true,
-    \\"host\\": \\"localhost\\",
+    \\"host\\": \\"local.host\\",
     \\"hotOnly\\": true,
     \\"inline\\": true,
     \\"noInfo\\": true,
     \\"overlay\\": Object {
       \\"errors\\": true,
       \\"warnings\\": true,
     },
     \\"port\\": 3000,

To:

 Object {
   "bail": false,
   "context": ".",
   "devServer": Object {
     "disableHostCheck": true,
-    "host": "localhost",
+    "host": "local.host",
     "hotOnly": true,
     "inline": true,
     "noInfo": true,
     "overlay": Object {
       "errors": true,
       "warnings": true,
     },
     "port": 3000,

I would love to add PR with this changes.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integration’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

An in-range update of babel7 is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.8.3 to 7.8.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the babel7 group definition.

babel7 is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of jest2 is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


There have been updates to the jest2 monorepo:

    • The dependency pretty-format was updated from 25.4.0 to 25.5.0.
  • The dependency jest-snapshot was updated from 25.4.0 to 25.5.0.
  • The dependency jest-diff was updated from 25.4.0 to 25.5.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the jest2 group definition.

jest2 is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for 25.5.0

Features

  • [@jest/globals] New package so Jest's globals can be explicitly imported (#9801)
  • [jest-core] Show coverage of sources related to tests in changed files (#9769)
  • [jest-runtime] Populate require.cache (#9841)

Fixes

  • [*] Use graceful-fs directly in every package instead of relying on fs being monkey patched (#9443)
  • [expect] Prints the Symbol name into the error message with a custom asymmetric matcher (#9888)
  • [jest-circus, jest-jasmine2] Support older version of jest-runtime (#9903 & #9842)
  • [@jest/environment] Make sure not to reference Jest types (#9875)
  • [jest-message-util] Code frame printing should respect --noStackTrace flag (#9866)
  • [jest-runtime] Support importing CJS from ESM using import statements (#9850)
  • [jest-runtime] Support importing parallel dynamic imports (#9858)
  • [jest-transform] Improve source map handling when instrumenting transformed code (#9811)

Chore & Maintenance

  • [docs] Add an example for mocking non-default export class

Performance

  • [jest-resolve] Update resolve to a version using native realpath, which is faster than the default JS implementation (#9872)
  • [jest-resolve] Pass custom cached realpath function to resolve (#9873)
  • [jest-runtime] Add teardown method to clear any caches when tests complete (#9906)
  • [jest-runtime] Do not pass files required internally through transformation when loading them (#9900)
  • [jest-runtime] Use Maps instead of object literals as cache holders (#9901)
Commits

The new version differs by 83 commits.

  • ddd73d1 v25.5.0
  • 2379d0d chore: update changelog for release
  • edf63d8 Make it easier to copy just one badge code (#9313)
  • 13d6194 Add an example for mocking non-default module export class (#9883)
  • 7e37b0f fix: use graceful-fs all over instead of monkey patching fs (#9443)
  • b4228da chore: use Maps rather than objects as cache holders (#9902)
  • e281d53 fix: do not transform internally imported files (#9900)
  • 752a176 minor typographical fix (#9909)
  • 6f5009b fix: hoist imports of @jest/globals correctly (#9806)
  • 5db005f chore: add teardown of jest-runtime (#9906)
  • 80dde6f fix: handle mismatch between circus and runtime versions (#9903)
  • ac267b1 Fix dead link to coverage CLI option (#9905)
  • faa5267 chore: remove dated node 6 reference from docs (#9895)
  • 4a142ec Use the new serializer plugin API in example (#9847)
  • 673eb49 chore: remove unused catch clauses (#9893)

There are 83 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Line Numbers for Differences Failing Test Unnecessarily

If I edit some irrelevant data, some lines are added to the snapshot and the snapshot diff test fails because the lines of the differences, for example,
@@ -7,30 +7,30 @@
are changed but nothing else. Are these lines really necessary?

"No visual difference" message outputting with color

This is more to note the regression than an issue to can be solved in this repo, other than rolling back the PR - looks like some of the diff output messages aren't controlled by the color options - https://github.com/facebook/jest/blob/4bd3d4a05999170f423f7050d4e0537648499e88/packages/jest-diff/src/constants.ts#L10-L11
jest-diff is using chalk.dim directly, rather than making use of the commonColor option which we're turning off when color is set to false (from PR #123).

The issue I'm seeing after upgrading is that we're getting a diff with color codes when running Jest normally (no colors when running CI=true)
image

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.6.1 to 16.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

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.