suchipi / chai-jest-snapshot Goto Github PK
View Code? Open in Web Editor NEWChai assertion that provides Jest's snapshot testing
License: MIT License
Chai assertion that provides Jest's snapshot testing
License: MIT License
Hey there! It would be great to integrate an optional deep-equal-in-any-order
functionality for snapshots as my CI fails now and then due to failing snapshots caused by this ordering issue. The data is actually correct and I don't care about the order.
Not sure if anyone else has come across this issue, but here's the current behaviour:
// test
const arrayOfObjects = [ { foo: "bar", id: 1 }, { foo: "bar", id: 2 }, { foo: "bar", id: 3 } ];
expect(arrayOfObjects).to.matchSnapshot();
// snapshot
exports[`should get objects`] = `
Object {
"locations": Array [
Object {
"foo": "bar",
"id": 1,
},
Object {
"foo": "bar",
"id": 2,
},
Object {
"foo": "bar",
"id": 3,
},
`;
// change order of objects
const arrayOfObjects = [
{ foo: "bar", id: 3 },
{ foo: "bar", id: 2 },
{ foo: "bar", id: 1 }
];
expect(arrayOfObjects).to.matchSnapshot();
// fails
Array [
Object {
"foo": "bar",
- "id": 3,
+ "id": 1,
},
Object {
"foo": "bar",
"id": 2,
},
Object {
"foo": "bar",
- "id": 1,
+ "id": 3,
},
]
Ideally, there would be an optional parameter to pass in such as matchSnapshot({ deepEqual: true })
that could potentially resolve this issue.
Thanks in advance for any replies/feedback!
Could you please add GitHub releases? They are automatically created when using Git tags.
They are great to receive new versions via an RSS reader.
Thanks for this great project!
This will enable the latest features
We've been using the library for a while now (and are quite happy about it ๐ ) but are facing some issues on the CI with snapshot files. This happens e.g. when someone forgets to add a scenario to a snapshot file or forgets commiting a snapshot file at all. I found out that Jest 20 supports the --ci
flag, would it be possible to add support in this library as well? I can help adding this feature but wasn't entirely sure where to start.
Our snapshot tests are failing due to ReferenceError: actual is not defined
.
ReferenceError: actual is not defined
at Proxy.matchSnapshot (node_modules/chai-jest-snapshot/dist/buildMatchSnapshot.js:45:12)
at Proxy.methodWrapper (node_modules/chai/lib/chai/utils/addMethod.js:57:25)
Started using chai-jest-snapshot
recently with mocha
, but I fear my colleagues will not like the additional effort of supplying a filepath & name for each snapshot.
Do you have any plans to allow a default / automatic filepath / name so that assertions can simply be made with:
expect(tree).to.matchSnapshot();
I'd love to help out if I can.
P.s. Additionally an easier way to update all snapshots would be nice, but I've not had any thoughts about ways to improve it yet. But if it were possible to do so with mocha -u
(or similar, as this is already used for --ui
), that'd be awesome.
Hi Stephen, first of all thank you for such a nice Chai plugin. Now I can easily extend my testing setup with snapshot testing of React components without switching to Jest (nothing bad about Jest but I have other tools in place already).
While writing tests with chaiJestSnapshot assertion I've encountered weird issue: I have four tests inside one describe
block and in every test I do snapshot assertion. Snapshot file name is the same for all four tests and is set for entire describe
block. Snapshot name is set per test four time and unique. When I run test without or with already rendered snapshot file I have only two snapshots out of four inside the snapshot file. When I try to change the name of snapshots and rerender snapshots (or render a new snapshot file), some of snapshots appear but I could not see a logic there.
Do you have any idea why this can happen?
works fine for me using chai 3.5.0...maybe make the peer dep >= 1.9.0?
I tried both Mocha configuration and framework-agnostic (manual) ones. Doesn't seem to work, as __dirname points to '/' which is not possible to write to (permission).
Any idea how to get it working with Mocha and Webpack? By the way, when I used the recommended way to configure it for Mocha, I got complaints that test name, snapshot name were not set. Apparently the before() beforeEach() were not run, however they were correctly configured as per suggested way.
Hey, we started using chai-jest-snapshots with TypeScript this week and ended up having to define our own types for them.
Would you like if I open a PR with the types for you?
Alternatively I could propose them to https://github.com/DefinitelyTyped/DefinitelyTyped/
I'd like to:
It seems that there is no way to accomplish it with this tool. Is there perhaps some other companion tool to help with that?
Alternatively, could such a support be added to chai-jest-snapshot
? I could help out with implementation...
I noticed that the imported SnapshotState
class has removeUncheckedKeys()
method, which seems to be doing exactly what is needed. But I guess one can't just call it from the matchSnapshot()
function in buildMatchSnapshot.js
, as then it would remove all the snapshots besides the current one that's tested.
I use Jest with Enzyme and when I use the following line like in the doc for updating my snapshot, that creates 1 more snapshot with the same name plus the true
string at the end:
expect(tree).to.matchSnapshot(true);
This test name
conversation destinated to a user 1
became:
conversation destinated to a user: true 1
I have a use case like so:
it('should make sure the return value doesnt change', async () => {
const resultPre = getResult()
expect(resultPre).to.matchSnapshot()
await runSomeSideEffect()
const resultPost = getResult()
expect(resultPost).to.matchSnapshot()
})
exports['should make sure the return value doesnt change 1'] = ...
exports['should make sure the return value doesnt change 2'] = ...
This works fine by ensuring that the snapshots do not change, but it duplicates what is the same output and gives a slightly misleading error if it fails.
It would be great if there was a way to specify reusing the same snapshot in different places. For example:
import { createSnapshotKey } from 'chai-jest-snapshot'
const snapshotKey = createShapshotKey()
it('should make sure the return value doesnt change', () => {
...
expect(resultPre).to.matchSnapshot(snapshotKey)
...
expect(resultPost).to.matchSnapshot(snapshotKey)
// both reference exports['should make sure the return value doesnt change 1']=...
})
Hello,
We noticed that after upgrading to v1.0.0, names of functions are now missing. For instance, where v0.3.0 would render [Function toolboxPressed]
, 1.0.0 just renders [Function]
for any function props.
Was this change intentional, and if so, what was the rationale? It seems like this makes snapshots less valuable for verifying if callback wiring has changed.
For some reason my snapshot always gets updated and my test will remain green. It does not matter whether I pass true to the matcher or don't.
I'm using 0.1.1 and I'm continuing investigating what is going on.
When I run mocha in watch mode, every new test run causes new snapshots to be written to .snap
files. So .snap
files grow over time even when no changes are made.
Running mocha manually every time doesn't add new ones, as expected.
mocha v3.2.0
chai v3.5.0
chai-jest-snapshot v0.3.0
I'll try investigating a little, let me know if I can provide more information.
These would not be committed, rather used for debugging.
Are there any plans to upgrade the version of jest-snapshot? I can see their API has changed quite a bit so it would involve potentially a bigger rewrite.
I ask because a feature like serializers would be really useful and I can see they aren't supported in v14 which it looks like you're using right now.
Does anyone have an example of configuring this package with Jest? I realize I can use the framework-agnostic version for Jest, but I'd prefer if someone has solved automating __filename
and test name so that I don't have to add that to every test.
Hello. Congrats for this amazing tool, cant wait to use it!
I tried including it in my current setup, runing tests with karma and mocha, and using Chai. You can see setup here:
https://github.com/davezuko/react-redux-starter-kit
The error comes when importing the module like the other ones:
wich should work perfectly. But I get a ton of errors:
WARNING in ./~/chai-jest-snapshot/~/jest-snapshot/build/SnapshotFile.js
Critical dependencies:
67:37-44 require function is used in a way in which dependencies cannot be statically extracted
@ ./~/chai-jest-snapshot/~/jest-snapshot/build/SnapshotFile.js 67:37-44
ERROR in ./~/chai-jest-snapshot/~/jest-snapshot/~/jest-util/build/index.js
Module not found: Error: Cannot resolve module 'fs' in /myProject/node_modules/chai-jest-snapshot/node_modules/jest-snapshot/node_modules/jest-util/build
@ ./~/chai-jest-snapshot/~/jest-snapshot/~/jest-util/build/index.js 13:11-24
SyntaxError: Unexpected token 'const'
at webpack:///~/chai-jest-snapshot/~/jest-snapshot/build/SnapshotFile.js:12:0 <- tests/test-bundler.js:113068
Apparently webpack is having some trouble using some core node modules?? Im very confused. Any light you could shed would be amazing.
thanks!
I didn't had that problem during dev time or release. But i'm exploring using snapshots for some tests and i'm given
node_modules\fbjs\lib\warning.js:33
Warning: Each child in an array or iterator should have a unique "key" prop. See https://fb.me/react-warning-keys for more information.
loading.tsx
import * as React from 'react';
import { Theme } from '@material-ui/core/styles/createMuiTheme';
import withStyles, { WithStyles } from '@material-ui/core/styles/withStyles';
import CircularProgress from '@material-ui/core/CircularProgress/CircularProgress';
import Typography from '@material-ui/core/Typography/Typography';
const styles = (theme: Theme) => ({
progressContainer: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
},
progress: {
margin: theme.spacing.unit * 2,
},
});
interface ILoadingProps {
message: string;
}
type PropsWithStyles = ILoadingProps &
WithStyles<'progressContainer' | 'progress'>;
const Loading = (props: PropsWithStyles) => {
const { classes, message } = props;
return (
<div className={classes.progressContainer} style={{ flexDirection: 'column' }}>
<CircularProgress className={classes.progress} size={50} />
<Typography>{message || 'Loading'}</Typography>
</div>
);
};
export default withStyles(styles)<ILoadingProps>(Loading);
loading.test.js
import * as React from 'react';
import { shallow } from 'enzyme';
import Loading from 'components/common/Loading';
import { expect } from 'chai';
import renderer from 'react-test-renderer';
const defaultMessage = "Loading";
const LoadingComponent = () => shallow(<Loading />);
describe('Component - Loading', () => {
const component = LoadingComponent();
/**
* should match default loading component with default message
*/
it('should match snapshot', () => {
const tree = renderer.create(component).toJSON();
expect(tree).to.matchSnapshot();
});
it('should render with default message (' + defaultMessage + ') when no messages are provided', () => {
expect(component.html()).to.contain(defaultMessage);
});
it('should render with custom message when message is provided', () => {
component.setProps({
message: 'testing loading',
});
expect(component.html()).to.contain(component.props().message);
});
});
If i remove the snapshot test case, i don't get such error, and if it helps, here's a copy of my .snap
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Component - Loading should match snapshot 1`] = `
<div
className="Loading-progressContainer-1"
style={
Object {
"flexDirection": "column",
}
}
>
<div
className="MuiCircularProgress-root-3 MuiCircularProgress-colorPrimary-6 MuiCircularProgress-indeterminate-5 Loading-progress-2"
role="progressbar"
style={
Object {
"height": 50,
"width": 50,
}
}
>
<svg
className="MuiCircularProgress-svg-8"
viewBox="22 22 44 44"
>
<circle
className="MuiCircularProgress-circle-9 MuiCircularProgress-circleIndeterminate-11"
cx={44}
cy={44}
fill="none"
r={20.2}
strokeWidth={3.6}
style={Object {}}
/>
</svg>
</div>
<p
className="MuiTypography-root-12 MuiTypography-body1-21"
>
Loading
</p>
</div>
`;
Jest currently has the functionality to pass a a flag to only regenerate snapshots of tests that match a certain pattern using the --testNamePattern
flag. It would be nice if this could also be possible using chai-jest-snapshot. It would definitely help some skeptical devs be more open to using mocha and this library for snapshot testing.
How would I use this with the assert
interface? I tried
assert.matchSnapshot(toJson(wrapper));
No go.
Hi!
This would be quite nice if it's possible. This line looks promising: https://github.com/suchipi/chai-jest-snapshot/blob/master/src/buildConfigState.js#L19 but haven't looked into it much.
I am using this package with Mocha, and setting a snap files explicitly using setFilename. When I run the tests, it shows as successful every time (even after changes). However, there are no snapshot files created anywhere in the directory structure.
Here's my setup -
I have a test_helper.js file -
const jsdom = require('jsdom');
const chai = require('chai');
const chaiImmutable = require('chai-immutable');
const chaiJestSnapshot = require('chai-jest-snapshot');
const React = require('react');
const doc = new jsdom.JSDOM('<!doctype html><html><body></body></html>');
const win = doc.window;
global.document = win.document;
global.window = win;
// Attach everything to the global object
if(window) {
Object.keys(window).forEach((key) => {
if (!(key in global)) {
global[key] = window[key];
}
});
}
chai.use(chaiImmutable);
chai.use(chaiJestSnapshot);
// You must use this Wrapper with functional react components
class Wrapper extends React.Component {
render() {
return this.props.children;
}
}
global.Wrapper = Wrapper;
A sample test file -
beforeEach(function(done) {
chaiJestSnapshot.configureUsingMochaContext(this);
chaiJestSnapshot.setFilename('test/actions/shared.snap');
done();
});
describe('actions/shared', function() {
it('passes the right rowIndex and type in openSettingsMenu', function() {
const rowIndex = 12;
const action = openSettingsMenu(rowIndex);
expect(action).to.matchSnapshot();
});
})
I'm compiling using webpack. This is the npm script -
"mocha-webpack --webpack-config webpack.test.config.js \"src/**/*.test.js\" --require 'test/test_helper.js'"
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.