Skip to content

Instantly share code, notes, and snippets.

@branneman branneman/_util.js
Created Oct 22, 2018

Embed
What would you like to do?
React + Apollo: Integration test without `await wait(0)` (and the waait dependency)
/**
* 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)
})
}
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!')
})
})
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
You can’t perform that action at this time.