Created
April 8, 2020 16:37
-
-
Save JimiSweden/aedf59cbe8f5201ab463078883a5ec72 to your computer and use it in GitHub Desktop.
Injecting context into mount using a wrapper function , testing react Browser dependent components, pattern for wrapping sub-components, enzyme, shallow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You can also use this pattern to wrap subcomponents in other types of context, | |
for example if you are using react-intl, material-ui or your own context types. | |
from: | |
https://stackoverflow.com/questions/50025717/jest-enzyme-invariant-violation-you-should-not-use-route-or-withrouter-ou | |
by: https://stackoverflow.com/users/8070554/steve-banton | |
Wrapping mount with Router in tests works, | |
but there are situations where you don't want Router to be the parent component in your mount. | |
Therefore I'm currently injecting context into mount using a wrapper function: | |
*/ | |
/** | |
testhelp/contextWrap.js | |
*/ | |
import { BrowserRouter } from 'react-router-dom'; | |
import Enzyme, { shallow, mount } from 'enzyme'; | |
import { shape } from 'prop-types'; | |
// Instantiate router context | |
const router = { | |
history: new BrowserRouter().history, | |
route: { | |
location: {}, | |
match: {}, | |
}, | |
}; | |
const createContext = () => ({ | |
context: { router }, | |
childContextTypes: { router: shape({}) }, | |
}); | |
export function mountWrap(node) { | |
return mount(node, createContext()); | |
} | |
export function shallowWrap(node) { | |
return shallow(node, createContext()); | |
} | |
/** | |
SomeFile.test.js | |
*/ | |
/** Example describe block: */ | |
import React from 'react'; | |
import { TableC } from '../../src/tablec'; | |
import { mountWrap, shallowWrap } from '../testhelp/contextWrap'; | |
import { expectedProps } from './mockdata' | |
describe('Table', () => { | |
let props; | |
let component; | |
const wrappedShallow = () => shallowWrap(<TableC {...props} />); | |
const wrappedMount = () => mountWrap(<TableC {...props} />); | |
beforeEach(() => { | |
props = { | |
query: { | |
data: tableData, | |
refetch: jest.fn(), | |
}, | |
}; | |
if (component) component.unmount(); | |
}); | |
test('should render with mock data in snapshot', () => { | |
const wrapper = wrappedShallow(); | |
expect(wrapper).toMatchSnapshot(); | |
}); | |
test('should call a DeepTable with correct props', () => { | |
const wrapper = wrappedMount(); | |
expect(wrapper.find('DeepTable').props()).toEqual(expectedProps); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment