Last active
September 14, 2018 08:50
-
-
Save isthatcentered/d0fd051b589e5bd24c06a19205d9e00b to your computer and use it in GitHub Desktop.
Mocking react 16 context in jest (typescript version)
This file contains 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
import * as React from "react" | |
import { mount } from "enzyme" | |
import StoreProvider from "./StoreProvider" | |
import Mock = jest.Mock | |
jest.mock( "./StoreProvider", () => ({ | |
default: { | |
// Using a jest mock function will allow us to assert on the mock later if needed | |
Consumer: jest.fn( | |
// This is mocking a component | |
// Ex: (props) => <div/> | |
// | |
// Consumer is a render prop component | |
// So we use the children prop as a function : | |
( { children } ) => | |
children( { user: "batman" } ), | |
), | |
}, | |
}) ) | |
const App = () => { | |
const { Consumer } = StoreProvider | |
return ( | |
<Consumer> | |
{ | |
( { user } ) => <div>{user}</div> | |
} | |
</Consumer> | |
) | |
} | |
describe( `Using mock`, () => { | |
beforeEach( () => { | |
// Clear all instances and calls to constructor and all methods: | |
(StoreProvider.Consumer as Mock).mockClear() | |
} ) | |
test( `Consumer is overriden and now returns only "batman"`, () => { | |
/** | |
* Returns : | |
* | |
* <App> | |
* <Consumer> | |
* <div> | |
* batman | |
* </div> | |
* </Consumer> | |
* </App> | |
*/ | |
const wrapper = mount( <App/> ) | |
expect( wrapper.text() ).toContain( "batman" ) | |
} ) | |
test( `Consumer has been called with a fonction as children`, () => { | |
// Full disclamer: this test is an example of what you can do. | |
// In real life it would a lot of work for not much value in this case | |
const wrapper = mount( <App/> ) | |
const expectedProps = { children: expect.anything() }, | |
expectedContext = {}, | |
firstCalledWith = (StoreProvider.Consumer as Mock).mock.calls[ 0 ] | |
expect( StoreProvider.Consumer ).toHaveBeenCalledWith( expectedProps, expectedContext ) | |
expect( typeof firstCalledWith[ 0 ].children ).toBe( "function" ) | |
} ) | |
} ) | |
// Jest has a very complete doc for mocks https://jestjs.io/docs/en/es6-class-mocks ☺️ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment