adriantoine / enzyme-to-json Goto Github PK
View Code? Open in Web Editor NEWSnapshot test your Enzyme wrappers
License: MIT License
Snapshot test your Enzyme wrappers
License: MIT License
Node 4 was removed in 1.6.0 without any mention of that in the change log. Itβs a breaking change so it should have been a major release.
Any reason to do that while Enzyme still supports Node 4?
Not sure if this is a bug or a feature but after updating to the latest version all my snapshots contains someProp={undefined}
for all props that are not defined in the test.
I was working on #63 and eventually decided to go for a slightly larger refactor of the library. It was started as simple quickly-made library and I was never expecting nearly 500 stars, so I think that it now needs a bit of polish. π
Here is a roadmap of everything I expect to be in the next major 3.0 release:
mount
wrappermountToShallowJson
and mountToDeepJson
and use options with {mode: 'shallow'|'deep'|'normal'}
insteadWarning: React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers. http://fb.me/react-polyfills
coming with React 16None yet
Components returning null
or any falsy value are now rendered as an empty string in snapshots instead of null
Shallow wrapper are now outputting undefined
props:
<BasicWithUndefined>
- <button>
+ <button
+ disabled={undefined}
+ >
Hello
</button>
</BasicWithUndefined>
This use case won't be supported anymore, it seems incorrect anyway to pass this
as a prop and I can see no usage of this in the react-bootstrap
documentation anyway
This use case won't be supported either as it doesn't seem to be supported by Enzyme either, you will just have to use their simulate
helper to do that
mountToShallowJson
and mountToDeepJson
are replaced by a mode
option in mountToJson
:
mountToShallowJson(wrapper);
// ==>
mountToJson(wrapper, {mode: 'shallow'});
mountToDeepJson(wrapper);
// ==>
mountToJson(wrapper, {mode: 'deep'});
All those changes will be made in the enzyme3
branch, I might create individual issues for some of those to track progress. I will also need a lot of testing with Enzyme 3 and React 16.
If anyone feels like working on any of the tasks above, please let me know! π
The first beta version has been released already π, you can test it with this command:
npm install --save-dev enzyme-to-json@next
I get a different snapshot depending on whether Jest is run with --coverage. Specifically, when Jest is run with --coverage
some but not all of the child components appear simply as <Component />
in the snapshot. When run without the --coverage
flag all of the child Components appear in the snapshot with the correct name. Additionally, the components that appear as <Component />
are all stateless functional components written as arrow functions. The child components that retain their name regardless of the coverage flag are class components. I've had a lot of trouble trying to reproduce this issue in a mock repo, but thought it would still be helpful to put it on the project's radar. I can currently avoid the issue by always running tests with or without the coverage flag, but when I switch between the two I need to also update snapshots.
Test case:
import React from 'react';
import toJson from 'enzyme-to-json';
import { shallow } from 'enzyme';
const arr = [
(
<React.Fragment>One</React.Fragment>
),
(
<React.Fragment>Two</React.Fragment>
),
];
const TestComponent = function ({ options }) {
return <div>{options[0]}</div>;
}
it('should not output UNDEFINED nodes', () => {
const component = shallow(
<div><TestComponent options={arr} /></div>
);
expect(toJson(component)).toMatchSnapshot();
});
Snapshot:
exports[`should not output UNDEFINED nodes 1`] = `
<div>
<TestComponent
options={
Array [
<UNDEFINED>
One
</UNDEFINED>,
<UNDEFINED>
Two
</UNDEFINED>,
]
}
/>
</div>
`;
This test, produces this snapshot. The div
root component of ClassWithPure is lost in the snapshot. It is a revival of #1 and this time, the only time to solve it is to dig even deeper in Enzyme containers.
I'd love to ignore some attributes when a component is serialized, for the purpose of keeping its snapshot focused and not cluttered with stuff like inline styles
For example:
<Dropzone multiple={false} accept="image/jpeg,image/png" onDrop={this.handleImageDrop}>
<ContentAdd style={addBtnStyle} />
</Dropzone>
Would serialize into:
<Dropzone
accept="image/jpeg,image/png"
multiple={false}
onDrop={[Function]}>
<ContentAdd
style={
Object {
"color": "#1ac5c0",
"height": 48,
"left": "33px",
"position": "absolute",
"top": "33px",
"width": 48,
}
} />
</Dropzone>
While i'd prefer:
<Dropzone
accept="image/jpeg,image/png"
multiple={false}
onDrop={[Function]}>
<ContentAdd
style={[object Object]}/>
</Dropzone>
I'm hesitant to open an issue for this - but after a few days of research don't have any other clues.
We are using Jest with Enzyme, and using enzyme-to-json to create snapshots of Enzyme wrappers.
When some of us create snapshots, we get 2 spaces per indentation. When others of us create the snapshots, we get 4 spaces per indentation.
Environment:
Is there an option in enzyme-to-json that specifies how much whitespace it uses?
Or has anyone experienced whitespace / formatting differences between machines?
I'm getting an error when I save the document without any modifications.
The only fact that I am saving it changes the snapshot and it returns as a "no match".
I am using enzyme-to-json
with a enzyme.mount
which is mounting:
<Provider store={store}>
<MemoryRouter>
<Component {...properties} />
</MemoryRouter>
</Provider>
Component
is a wrapped redux-form
container:
reduxForm({
form: 'myForm',
validate
})(MyComponent)
The errors are:
β <ForgotPassword /> βΊ render βΊ should render correctly all
expect(value).toMatchSnapshot()
Received value does not match stored snapshot 1.
- Snapshot
+ Received
@@ -37,11 +37,11 @@
"canGo": [Function],
"createHref": [Function],
"entries": Array [
Object {
"hash": "",
- "key": "yhrazi",
+ "key": "wegq0d",
"pathname": "/",
"search": "",
"state": undefined,
},
],
@@ -51,11 +51,11 @@
"index": 0,
"length": 1,
"listen": [Function],
"location": Object {
"hash": "",
- "key": "yhrazi",
+ "key": "wegq0d",
"pathname": "/",
"search": "",
"state": undefined,
},
"push": [Function],
at Object.<anonymous> (tests/renderers/authentication/forgotPassword.tests.js:71:52)
at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
at process._tickCallback (internal/process/next_tick.js:109:7)
Am I doing something wrong?
I noticed the new map function, which is super useful! However, it has limited use with the values that are provided. Something that might be useful would be exposing the raw node, so that you just have more information available to work with, and could do things like stripping defaultProps.
I"m getting this error when trying to install dependencies. I upgraded 4 hours ago to version 3.3.2
and now it seems to be breaking with the following error.
error An unexpected error occurred: "Couldn't find any versions for \"enzyme-to-json\" that matches \"3.3.2\"".
info If you think this is a bug, please open a bug report with the information provided in "/Users/ifiokjr/Coding/primarybid/PrimaryBid/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/upgrade-interactive for documentation about this command.
For now, I've downgraded to 3.3.1
as a temporary fix.
Recently, we got an exception looks like:
TypeError: Cannot convert undefined or null to object
at Object.<anonymous> (__tests__/container/list/AccountsList.test.js:105:89)
at process._tickCallback (internal/process/next_tick.js:103:7)
Some people reports to enzyme at enzymejs/enzyme#750 .
Hi there! Just discovered this and I'm excited to use it! I bumped into a problem.
Given this component:
import React, {PropTypes, Component} from 'react'
class Toggle extends Component {
constructor(props) {
super(props)
this.state = {
toggledOn: props.initialToggledOn || false,
}
}
handleToggleClick = () => {
const toggledOn = !this.state.toggledOn
this.props.onToggle(toggledOn)
this.setState({toggledOn})
};
render() {
const {children} = this.props
const {toggledOn} = this.state
const onOff = toggledOn ? 'on' : 'off'
const toggledClassName = `toggle--${onOff}`
return (
<div className={`toggle ${toggledClassName}`}>
<button onClick={this.handleToggleClick}>
{children}
</button>
</div>
)
}
}
Toggle.propTypes = {
initialToggledOn: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
children: PropTypes.any.isRequired,
}
export default Toggle
And these tests:
import React from 'react'
import {mount} from 'enzyme'
import {mountToJson} from 'enzyme-to-json'
import Toggle from './Toggle'
test('invokes the onToggle prop when clicked', () => {
const onToggle = jest.fn()
const wrapper = mountToggle({onToggle})
clickButton(wrapper)
expect(onToggle).toHaveBeenCalledTimes(1)
expect(onToggle).toBeCalledWith(true)
})
test('changes the class to toggle--on when clicked', () => {
const wrapper = mountToggle()
clickButton(wrapper)
expect(mountToJson(wrapper)).toMatchSnapshot()
})
/**
* Uses enzyme to mount the Toggle component
* @param {Object} props - the props to mount the component with
* @return {Object} - the enzyme wrapper
*/
function mountToggle(props = {}) {
return mount(
<Toggle onToggle={() => {}} {...props}>Toggle Me</Toggle>
)
}
/**
* finds the button in the given wrapper and simulates a click event
* @param {Object} wrapper - the enzyme wrapper
*/
function clickButton(wrapper) {
wrapper.find('button').first().simulate('click')
}
I'm getting this snapshot:
exports[`test changes the class to toggle--on when clicked 1`] = `
<Toggle
onToggle={[Function onToggle]}>
<button
onClick={[Function anonymous]} />
</Toggle>
`;
Before, I was just using expect(wrapper.html()).toMatchSnapshot()
and got this snapshot:
exports[`test changes the class to toggle--on when clicked 1`] = `"<div class=\"toggle toggle--on\"><button>Toggle Me</button></div>"`;
The major issue here is that with the snapshot generated from mountToJson
doesn't tell me the root node's a div
and that it has a className
.
Any ideas? Thanks again for this module.
It seems like I can generate snapshots just fine without using toJson
.
const component = shallow(<Component />)
expect(component).toMatchSnapshot()
Is this a valid way to use the serializer?
I'm going to preface this with something that I'm doing is probably horribly outside of the box for a React app.
I am using rc-tooltip but require that I mount it to a place other than document.body
. To do this, I keep a mountNode and pass it down to tooltip users. My PropTypes looks like:
mountNode: PropTypes.instanceOf(window.Node).isRequired,
I create a component instance with the following mountNode
prop:
mountNode={document.createElement('div')}
Upon doing so, I get this error from the toMatchSnapshot:
TypeError: Cannot convert undefined or null to object
I don't believe that this error is coming directly from enzyme-to-json, but it seems something it is passing is unexpected in the snapshot? When I replaced the createElement with a string, it works but I get a PropTypes warning.
shallowToJson
fails if a function component returns null.
at nodeToJson (node_modules/enzyme-to-json/build/shallow.js:32:36)
at shallowToJson (node_modules/enzyme-to-json/build/shallow.js:44:12)
I am using enzyme for testing after making a change from react-test-renderer.
Initially I want to snapshot test (pure-html) all components and once complete move onto more detailed tests.
My issue is mount is going to be great for more detailed testing but I do not see why render which returns the html does not also use the life-cycle methods as these are needed with HOC or with redux to properly render a component.
Would you be open to the addition of some form of node mapping functionality added on top of the existing serialization? Here are some use cases that I've run into where something like this could be really useful:
I'm sure there are all sorts of other use-cases that people could come up with. It would be awesome if you could specify a function somewhere that would be called for each transformed node and would have access to the raw node as well as the default JSON output which it could transform.
If this is something you would be amenable to I'd be happy to open a PR.
In the version 2.6 of TypeScript, they changed the way they perform type checking for function (see https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#strict-function-types). As a result code using toJson
with a generic version of ComponentWrapper will not compile.
[ts]
Argument of type 'ReactWrapper<AppStore, {}>' is not assignable to parameter of type 'CommonWrapper<{}, {}>'.
Types of property 'filterWhere' are incompatible.
Type '(predicate: (wrapper: ReactWrapper<AppStore, {}>) => boolean) => ReactWrapper<AppStore, {}>' is not assignable to type '(predicate: (wrapper: CommonWrapper<{}, {}>) => boolean) => CommonWrapper<{}, {}>'.
Types of parameters 'predicate' and 'predicate' are incompatible.
Types of parameters 'wrapper' and 'wrapper' are incompatible.
Type 'ReactWrapper<AppStore, {}>' is not assignable to type 'CommonWrapper<{}, {}>'.
I tried switching from Jest but when I do my test never completes.
it("should render a cell correctly in workflow mode", () => {
const component = shallow(<ReactBoardCellComponent
{...props}
/>);
expect(toJson(component)).toMatchSnapshot();
});
$ yarn test
yarn test v0.27.5
$ jest
RUNS src/components/__tests__/boardcell.test.tsx <-- Never completes
^C
enzyme 2.8.2
enzyme-to-json 1.5.1
jest 20.0.4
If I add a key
prop, it's not serialized to the snapshot.
Steps
expect(<div />).toMatchSnapshot()
expect(<div key={1} key2={1} />).toMatchSnapshot()
Expected:
Diff should show also + key={1}
Snapshot serializer in jest-config.json
"snapshotSerializers": ["<rootDir>/node_modules/jest-serializer-enzyme"]
jest: 20.0.4
jest-serializer-enzyme: 1.0.0
enzyme-to-json: 1.5.1
Before anyone opens an issue, I'm aware the serializer added earlier on doesn't work as expected, I'm looking into it π€
Enzyme recently picked up changes in v2.6.0 that remove the need for .update() in the shallow wrapper for a lot of cases. It accomplishes this by replacing the node and nodes properties with functions (getNode and getNodes) that always return the latest output of the underlying shallow renderer.
To keep back-compat with other versions of enzyme, one could simply check for .getNode and fall back to .node if it's not there.
Example:
const wrapper = shallow(<MyComponent />);
wrapper.find(Child).props().methodThatSetsStateOnMyComponent();
wrapper.update(); //shallow DOM won't be updated in the snapshot without this
expect(shallowToJson(wrapper)).toMatchSnapshot();
With the proposed change, we wouldn't need the .update() call.
This issue is probably related to #30.
When we invoke find()
on enzyme's wrapper and get multiple nodes in return, enzyme-to-json
only handles the first node.
For example:
const App = () => (
<div>
<ul>
<li>0</li>
<li>1</li>
</ul>
</div>
);
const wrapper = mount(App);
When I call
expect(renderToJson(wrapper.find('li'))).toMatchSnapshot();
I expects to get something like
Array[
<li>0</li>,
<li>1</li>
]
but I get
<li>0</li>
It's because this line
We can change this behavior by checking the length of the wrapper first. In my mind, it would be something like:
if (wrapper.length > 1) {
wrapper.nodes.map(toJson)
} else {
toJson(wrapper.node)
}
I would like to create a PR with related tests if this looks good to you.
Hi! Thanks for the wonderful work on this package! I prefer it to react-test-renderer
because all of my tests leverage enzyme so it's one single way of doing things.
However, I believe I stumbled across a bug where a value of just 0
as children does not get serialized to JSON. Here's a minimal contrived example:
it('dummy', () => {
const TestComponent = ({number = 0}) => (
<div>{number}</div>
);
let wrapper = mount(<TestComponent />);
console.log(toJson(wrapper.find('div')));
// this passes
expect(wrapper.find('div').text()).toBe('0');
});
In the console:
Object {
type: 'div',
props: Object {},
children: null,
'$$typeof': Symbol(react.test.json) }
Interestingly enough, if I do number.toString()
it works as expected. So something somewhere is doing a falsy check π
Thanks!
Hello,
While comparing the rendered output of enzyme-to-json
(enzyme mount) with react-test-renderer
, I see the snapshot though enzyme-to-json contains all the HOC and other react components. This causes two issues
Is there a way to only output real dom nodes if one uses mount
?
thanks.
Just wondering if it's possible to publish 3.3.3. We have some folks with yarn caches that say that 3.3.2 is valid, and it's troublesome to invalidate the cache due to the rollback.
If we publish 3.3.3 (even if the same code), folks should automatically be upgraded.
Hi,
I have a bit of a complex component, which renders pretty printed message with enzyme w.debug()
. But, getting following stack when use with mountToJson
const w = mount(<MyComponent ... />);
// console.log(w.debug());
expect(mountToJson(w)).toMatchSnapshot();
can you give some pointers to identify the issue without a test repo :-)
thanks.
bsr.
TypeError: renderedChildren[key].getPublicInstance is not a function
at node_modules/enzyme/build/MountedTraversal.js:153:40
at Array.map (native)
at node_modules/enzyme/build/MountedTraversal.js:149:12
at childrenOfInstInternal (node_modules/enzyme/build/MountedTraversal.js:156:6)
at childrenOfInstInternal (node_modules/enzyme/build/MountedTraversal.js:160:12)
at childrenOfInst (node_modules/enzyme/build/MountedTraversal.js:179:10)
at ReactWrapper.<anonymous> (node_modules/enzyme/build/ReactWrapper.js:818:55)
at node_modules/enzyme/build/ReactWrapper.js:1190:21
at Array.map (native)
at ReactWrapper.flatMap (node_modules/enzyme/build/ReactWrapper.js:1189:32)
at ReactWrapper.children (node_modules/enzyme/build/ReactWrapper.js:817:32)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:52)
at ReactWrapper.<anonymous> (node_modules/enzyme-to-json/build/index.js:34:16)
at node_modules/enzyme/build/ReactWrapper.js:1043:21
at Array.map (native)
at ReactWrapper.map (node_modules/enzyme/build/ReactWrapper.js:1042:27)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:63)
at ReactWrapper.<anonymous> (node_modules/enzyme-to-json/build/index.js:34:16)
at node_modules/enzyme/build/ReactWrapper.js:1043:21
at Array.map (native)
at ReactWrapper.map (node_modules/enzyme/build/ReactWrapper.js:1042:27)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:63)
at ReactWrapper.<anonymous> (node_modules/enzyme-to-json/build/index.js:34:16)
at node_modules/enzyme/build/ReactWrapper.js:1043:21
at Array.map (native)
at ReactWrapper.map (node_modules/enzyme/build/ReactWrapper.js:1042:27)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:63)
at ReactWrapper.<anonymous> (node_modules/enzyme-to-json/build/index.js:34:16)
at node_modules/enzyme/build/ReactWrapper.js:1043:21
at Array.map (native)
at ReactWrapper.map (node_modules/enzyme/build/ReactWrapper.js:1042:27)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:63)
at ReactWrapper.<anonymous> (node_modules/enzyme-to-json/build/index.js:34:16)
at node_modules/enzyme/build/ReactWrapper.js:1043:21
at Array.map (native)
at ReactWrapper.map (node_modules/enzyme/build/ReactWrapper.js:1042:27)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:63)
at ReactWrapper.<anonymous> (node_modules/enzyme-to-json/build/index.js:34:16)
at node_modules/enzyme/build/ReactWrapper.js:1043:21
at Array.map (native)
at ReactWrapper.map (node_modules/enzyme/build/ReactWrapper.js:1042:27)
at shallowToJson (node_modules/enzyme-to-json/build/index.js:33:63)
I get below error in my test suite:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
SyntaxError: Unexpected token ','
at webpack:///node_modules/enzyme-to-json/shallow.js:61:0 <- test-bundler.js:335737
am using:
"react": "16.2.0",
"enzyme": "3.2.0",
"enzyme-adapter-react-16": "1.1.0",
"enzyme-to-json": "3.3.0",
Additional info:
my node version: v8.9.3
babel: 6.x
babel-preset-env: 1.6.x
After playing around i found that:
So, i dug deeper and fix below 3 lines in 3 different files of enzyme-to-json
package in my local node_modules, and my test cases with PhantomJS starts running.
enzyme-to-json/shallow.js (https://github.com/adriantoine/enzyme-to-json/blob/v3.3.0/src/shallow.js#L48):
original code = node,
replaced with: node: node,
enzyme-to-json/mount.js (https://github.com/adriantoine/enzyme-to-json/blob/master/src/mount.js#L57):
original code = node,
replaced with: node: node,
enzyme-to-json/createSerializer.js (https://github.com/adriantoine/enzyme-to-json/blob/master/src/createSerializer.js#L6)
original code = test(wrapper) {
replaced with = test: function (wrapper) {
Also, at (https://github.com/adriantoine/enzyme-to-json/blob/master/src/createSerializer.js#L9)
original code = print(wrapper, serializer) {
replaced with = print: function (wrapper, serializer) {
I am not sure where exactly the problem is.
Kindly, do let me know if am missing something here or any more information is required.
Thanks in advance.
Hi.
I have two components:
const A = props => <div><B firstProps="a" /></div>;
const B = props => <div />;
B.defaultProps = {
secondProps: "b"
};
Snapshot of A
I would expect:
<div>
<B
firstProps="a" />
</div>
Snapshot of A
I got:
<div>
<B
firstProps="a"
secondProps="b" />
</div>
Note how B
s defaultProps
are visible in shallow render of A
, even though I did not pass them in A
. This is very bad, since it exposes internals of B
. When I change implementation of B
it should only affect B
s tests (this is the whole reason why I use shallow render), but currently if I change defaultProps
it will affect tests of every component that uses B
.
Only props really passed in A
should be visible in snapshot.
Thoughts?
Have a good day, everyone. ;)
Hello is it possible to configure serializer to skip element attributes? It would be wonderful to get on snapshot only elements and innerText.
<ul
className="bottomMasked"
id="agentsList"
onScroll={[Function]}
>
<li
className={null}
onClick={[Function]}
>
Detective Inspector Lee
</li>
</ul>
I use Jest to mock out some child components, with the react-test-renderer
I got
<mocked someProps="someString" />
using enzyme
and shallowToJson
I got:
<function (props) {return (/* istanbul ignore next */_react2.default.createElement( /* istanbul ignore next */'mocked', /* istanbul ignore next */_extends({ originalComponent: componentName }, props), props.children));} someProps="someString" />
Do you think its possible to recognise mocks and render they just like the react-test-renderer
.
Version 3.3.3 changed the behavior regarding default props which breaks snapshots.
[email protected] Fragments fail to serialize.
TypeError: Cannot convert a Symbol value to a string
import React, { Fragment } from 'react';
import { shallow } from 'enzyme';
function AnotherComponent() {
return (
<Fragment>
<li>First</li>
<li>Second</li>
</Fragment>
);
}
function Component() {
return (
<ul>
<AnotherComponent />
</ul>
);
}
test('renders', () => {
const wrapper = shallow(<Component />)
.find('AnotherComponent')
.dive();
expect(wrapper).toMatchSnapshot();
});
Just though this maybe more relevant here as @kentcdodds says it doesn't happen with react-test-renderer
. Hope you can identify the cause in this case as it only happens with enzyme-to-json
.
please see jestjs/jest#1780 for details
Using the latest enzyme
master
, which includes fixes for React 15.5 raises the following error when running tests:
Cannot find module 'enzyme/build/ShallowWrapper' from 'utils.js'
I'll see if I can raise a PR to fix this once I figure out where the ShallowWrapper
has moved to
Hi There
Apologies in advance if this isn't per format or I should ask elsewhere.
I am having an issue as I progress towards moving a React 15.6.1 project to React 16. As part of this I have updated Babel, Chai, Enzyme etc. - When I run the test suite, I end up with the following:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
SyntaxError: Unexpected token ','
at webpack:///node_modules/enzyme-to-json/shallow.js:61:0 <- test-bundler.js:335732
The error is on this line:
https://github.com/adriantoine/enzyme-to-json/blob/v3.3.0/src/shallow.js#L48
Changing node,
to node:node
resolves this error but it moves them to the next set of files.
It feels like a transpiling issue.
test-bunder.js
import 'babel-polyfill';
import chai from 'chai';
import sinon from 'sinon';
import chaiEnzyme from 'chai-enzyme';
import sinonChai from 'sinon-chai';
import { matchSnapshot } from 'chai-karma-snapshot';
chai.use(chaiEnzyme());
chai.use(sinonChai);
chai.use(matchSnapshot);
global.sinon = sinon;
global.expect = chai.expect;
const context = require.context('../../app', true, /\.jsx?$/);
context.keys().forEach(context);
This issue may related to #17.
Following test:
const App = () => (
<div>
<ul>
<li>0</li>
<li>1</li>
</ul>
</div>
);
const wrapper = render(App);
expect(renderToJson(wrapper.find('ul'))).toMatchSnapshot();
Generated snapshot:
<li>0</li>
I'd expect the generated snapshot contains the whole ul
node.
When tested using Jest snapshots i observe different behaviour when I run the tests with --coverage flag or without.
With coverage flag i get Component
in first child
Without coverage flag i get true React component ModalHeader
jest configuration:
jest version = 16.0.0
test framework = jasmine2
config = {
"collectCoverageFrom": [
"app/*/.{js,jsx}",
"!app/app.js",
"!app/routes.js"
],
"moduleDirectories": [
"node_modules",
"/Users/romario/Projects/work/imtm/app"
],
"moduleNameMapper": [
[
"..css$",
"/Users/romario/Projects/work/imtm/mocks/cssModule.js"
],
[
"..jpg|..png$",
"/Users/romario/Projects/work/imtm/mocks/image.js"
]
],
"setupTestFrameworkScriptFile": "/Users/romario/Projects/work/imtm/internals/testing/test-bundler.js",
"testRegex": "tests/..test.js$",
"rootDir": "/Users/romario/Projects/work/imtm",
"name": "-Users-romario-Projects-work-imtm",
"setupFiles": [
"/Users/romario/Projects/work/imtm/node_modules/babel-polyfill/lib/index.js"
],
"testRunner": "/Users/romario/Projects/work/imtm/node_modules/jest-jasmine2/build/index.js",
"scriptPreprocessor": "/Users/romario/Projects/work/imtm/node_modules/babel-jest/build/index.js",
"usesBabelJest": true,
"automock": false,
"bail": false,
"browser": false,
"cacheDirectory": "/var/folders/zb/cdw729m57bg8thqz6f863w3c0000gn/T/jest",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"globals": {},
"haste": {
"providesModuleNodeModules": []
},
"mocksPattern": "mocks",
"moduleFileExtensions": [
"js",
"json",
"jsx",
"node"
],
"modulePathIgnorePatterns": [],
"noStackTrace": false,
"notify": false,
"preset": null,
"preprocessorIgnorePatterns": [
"/node_modules/"
],
"resetModules": false,
"testEnvironment": "jest-environment-jsdom",
"testPathDirs": [
"/Users/romario/Projects/work/imtm"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testURL": "about:blank",
"timers": "real",
"useStderr": false,
"verbose": null,
"watch": false,
"cache": true,
"watchman": true,
"testcheckOptions": {
"times": 100,
"maxSize": 200
}
}
In the snapshots many of my strings are surrounded by <!-- react-text: [number] -->
comments. These comments tend to change often for unrelated reasons, causing the snapshots to break. Is it possible to omit these comments from the output?
Hey, I'm not sure if this is a bug but there seems to be some inconsistency between the code and described behaviour.
In the recent version 3.0 upgrade Issue #67, one of the breaking changes is: "Components returning null or any falsy value are now rendered as an empty string in snapshots instead of null"
But that doesn't seem to be what's happening in the code.
A simple failing case:
const MyComponent = ({ foo }) => {
return (
foo && <div>Yep</div>
);
};
it("truthy case", () => {
const myComponent = shallow(
<MyComponent foo />,
);
expect(toJson(myComponent)).toMatchSnapshot();
});
it("falsey case", () => {
const myComponent = shallow(
<MyComponent foo={false} />,
);
expect(toJson(myComponent)).toMatchSnapshot();
});
gives
exports[`truthy case 1`] = `
<div>
Yep
</div>
`;
exports[`falsey case 1`] = `undefined`;
where I would expect falsey case
to return the empty string.
I think this is because we're using lodash
's isNil
to check return values here
Line 39 in 810b38a
which "Checks if value is null or undefined." but not false
: https://lodash.com/docs/4.17.4#isNil
Is using isNil
desired behaviour? Thanks for your time
I'm trying to snapshot a routed redux app, my test code is as follows:
const app = mount(renderApp());
const tree = enzymeToJson(app);
const snapshotFileName = path.join(__dirname, "App.enzyme.js.snap");
const snapshotName = "Enzyme App renders correctly";
expect(tree).to.matchSnapshot(snapshotFileName, snapshotName);
I'm using chai-jest-snapshot to do the snapshotting. The output I see in the snapshot file looks like this:
exports[`Enzyme App renders correctly`] = `
<Provider
store={
Object {
"@@reduxReactRouter/routerStateSelector": [Function routerStateSelector],
"dispatch": [Function anonymous],
"getState": [Function getState],
"history": Object {
"__v2_compatible__": true,
"createHref": [Function createHref],
"createKey": [Function createKey],
"createLocation": [Function createLocation],
...
Snapshot testing fails because some key values differ on each test execution.
However when I use react-test-renderer the snapshot output is just HTML and the snapshot comparisons work fine:
exports[`Jest App renders correctly`] = `
<div
id="app-container">
<nav
className="PageHeader navbar navbar-inverse navbar-fixed-top">
<div
className="container-fluid">
<div
className="navbar-header">
<span
className="navbar-brand">
<div
className="PageHeader-logo" />
<span
...
The code I ran to produce this is:
const tree = renderer.create(renderApp()).toJSON();
const snapshotFileName = path.join(__dirname, "App.jest.js.snap");
const snapshotName = "Jest App renders correctly";
expect(tree).to.matchSnapshot(snapshotFileName, snapshotName);
So the only difference appears to be calling the enzymeToJson()
method rather than using the react-test-renderer equivalent.
Any help gratefully received.
This is the same bug that is fixed in enzymejs/enzyme#476
With the change from #1 I get the following error when using shallowToJson
with nested components:
TypeError: Cannot read property 'type' of undefined
at shallowToJson (node_modules/enzyme-to-json/build/index.js:57:22)
Was upgrading an app to React@16 and came across what seems to be a bug with the latest enzyme-to-json
(or enzyme) where snapshots for arrays are missing some elements.
Would be happy to contribute, just want to understand if this is an issue with enzyme-to-json
or enzyme
's childrenOfNode?
I can't seem to get enzyme to render with the checked attribute of an input. I've tried:
<input type="checkbox" checked="checked" value="party" id="party-button" disabled="disabled" />
and it'll render as (without the checked):
<input disabled="" id="party-button" type="checkbox" value="party" />
I tried these variations and they all render the same thing:
<input type="checkbox" checked={true} value="party" id="party-button" disabled />
<input type="checkbox" checked="checked" value="party" id="party-button" disabled={true} />
This was discovered in 3.3.2 that is no longer out. (See comments on f5181d4)
When the snapshots got created the default props containing Object {}
, [Function]
and boolean values seems to be removed but not the empty strings.
In our component Image we have default props:
Image.defaultProps = {
className: '',
caption: '',
style: {},
};
Snapshot for version 3.3.1:
<Image
caption=""
className=""
height={60}
style={Object {}}
width={60}
/>
Snapshot for version 3.3.2
<Image
caption=""
className=""
height={60}
width={60}
/>
I get this error in all my test suites using [email protected]
, [email protected]
(unmet peer dependency), and [email protected]
(unmet peer dependency).
Cannot find module 'enzyme/build/ShallowTraversal' from 'shallow.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (node_modules/enzyme-to-json/build/shallow.js:25:25)
While it's clear to me that the peer dependencies are intentionally not supporting these unstable versions yet, it would be helpful to start working on support in a prerelease so projects testing React 16 and projects forced to use it because of React Native can continue to use this project until React and Enzyme are stable.
Getting error: Error: Invalid Chai property: toMatchSnapshot
import toJson from 'enzyme-to-json';
describe('Component Snapshot', () => {
const wrapper = mount(\<Component /\>);
const instance = wrapper.instance();
it('should generate shapshot', () => {
expect(toJson(wrapper)).toMatchSnapshot()
});
});
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.