Created
October 22, 2018 15:40
-
-
Save branneman/bb7b91617d9a47e650abeb9cf1bbaad4 to your computer and use it in GitHub Desktop.
React + Apollo: Integration test without `await wait(0)` (and the waait dependency)
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
/** | |
* This function polls the component's props for Apollo to set `props.data.loading` to `false` | |
* @example | |
* await waitDuringLoadingState(testRenderer, TodoContainer) | |
* @see {@link https://reactjs.org/docs/test-renderer.html} | |
* @param {TestRenderer} testRenderer | |
* @param {React.Component} testComponent | |
* @returns {Promise} | |
*/ | |
export function waitDuringLoadingState(testRenderer, testComponent) { | |
const testInstance = testRenderer.root.findByType(testComponent) | |
return new Promise(resolve => { | |
const interval = setInterval(() => { | |
if (testInstance.props.data.loading === false) { | |
clearInterval(interval) | |
resolve() | |
} | |
}, 10) | |
}) | |
} |
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 { waitDuringLoadingState } from '_util' | |
describe('Container / Todo', () => { | |
it('should render loading state', () => { | |
const testRenderer = TestRenderer.create( | |
<MockedProvider mocks={getTodoQueryMock} addTypename={false}> | |
<Todo /> | |
</MockedProvider> | |
) | |
const tree = testRenderer.toJSON() | |
expect(tree.children).toContain('Loading...') | |
}) | |
it('should render the finished state', async () => { | |
const tree = TestRenderer.create( | |
<MockedProvider mocks={getTodoQueryMock} addTypename={false}> | |
<Todo /> | |
</MockedProvider> | |
) | |
await waitDuringLoadingState(tree, TodoContainer) | |
const tree = testRenderer.toJSON() | |
expect(tree.children).toContain('Finished!') | |
}) | |
}) |
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
export const getTodoQuery = gql`...` | |
export const addTodoMutation = gql`...` | |
export class TodoContainer extends React.Component { | |
render() { | |
if (this.props.data.loading) { | |
return <div>Loading...</div> | |
} | |
return <div>Finished!</div> | |
} | |
} | |
export default compose( | |
graphql(getTodoQuery), | |
graphql(addTodoMutation, { | |
name: 'addTodoMutation', | |
options: { refetchQueries: [{ query: getTodoQuery }] } | |
}) | |
)(TodoContainer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment