Skip to content Skip to sidebar Skip to footer

Write A Jest Test To My First Component

I just finished writing my first Reactjs component and I am ready to write some tests (I used material-ui's Table and Toggle). I read about jest and enzyme but I feel that I am sti

Solution 1:

fetch is supported in the browser, but jest/enzyme run in a Node environment, so fetch isn't a globally available function in your test code. There are a few ways you can get around this:

1: Globally mock fetch - this is probably the simplest solution, but maybe not the cleanest.

global.fetch = jest.fn().mockResolvedValue({
  json: () =>/*Fake test data*/// or mock a response with `.text()` etc if that's what// your initializeData function uses
});

2: Abstract your fetch call into a service layer and inject that as a dependency - This will make your code more flexible (more boilerplate though), since you can hide fetch implementation behind whatever interface you choose. Then at any point in the future, if you decide to use a different fetch library, you can swap out the implementation in your service layer.

// fetchService.jsexportconstfetchData = (url) => {
  // Simplified example, only takes 'url', doesn't// handle errors or other params.returnfetch(url).then(res => res.json());
}

// MyComponent.jsimport {fetchService} from'./fetchService.js'classMyComponentextendsReact.Component {
  static defaultProps = {
    // Pass in the imported fetchService by default. This// way you won't have to pass it in manually in production// but you have the option to pass it in for your tests
    fetchService
  }
  ...
  initializeData() {
    // Use the fetchService from propsthis.props.fetchService.fetchData('some/url').then(data => {
      this.setState({ data });
    })
  }
}

// MyComponent.jest.jsit('myFirstTest', () => {
  const fetchData = jest.fn().mockResolvedValue(/*Fake test data*/);
  const fetchService = { fetchData };
  const wrapper = mount(<MyComponentfetchService={fetchService} />);
  returnPromise.resolve().then(() = {
    // The mock fetch will be resolved by this point, so you can make// expectations about your component post-initialization here
  })
}

Post a Comment for "Write A Jest Test To My First Component"