mardi 6 novembre 2018

How to mock a server call that happens deep in an import tree?

I am trying to test a component that relies on a store that connects to the server to retrieve data in its constructor. I am using Jest and Enzyme.

The component looks like this:

import React, { Component } from 'react'
import { observer, inject } from 'mobx-react'

@inject('Store')
@observer
class ExampleComponent extends Component {
  get words() {
    return this.props.Store.words
  }

  render() {
    return (
      {this.words.map(word => <div>word</div>)}
    )
  }
}

export default ExampleComponent

The store looks something like this:

import { action, observable } from 'mobx'
import Collection from './Collection'

class CensorStore {
  constructor() {
    Collection.getWords().then(action(words => { this.words = words }))
  }

  @observable words = ''
}

export default new CensorStore()

Collection looks something like this:

import connection from './connection.jsx

const getWords = async () => {
  const response = await.connection.get('/getURl')

  return response.data.data
}

export default { getWords }

And I would like to test it by doing something like this:

import React from 'react'
import { shallow } from 'enzyme'
import ExampleComponent from './ExampleComponent'
import Store from './Store'

it('renders correctly', () => {
  const wrapper = shallow(<ExampleComponent Store={Store} />

  expect(wrapper).toMatchSnapShot()
}

The issue is that when I import Store that triggers a chain of imports that eventually gets to connection which initiates a get request. How can I prevent this? I know I can mock that connection, but is this possible to mock the connection that deep in the import cycle? Any help is greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire