Posts

Showing posts with the label jestjs

How to unit test a React component that renders after fetch has finished?

How to unit test a React component that renders after fetch has finished? I'm a Jest/React beginner. In jest's it I need to wait until all promises have executed before actually checking. it My code is similar to this: export class MyComponent extends Component { constructor(props) { super(props); this.state = { /* Some state */ }; } componentDidMount() { fetch(some_url) .then(response => response.json()) .then(json => this.setState(some_state); } render() { // Do some rendering based on the state } } When the component is mounted, render() runs twice: once after the constructor runs, and once after fetch() (in componentDidMount() ) finishes and the chained promises finish executing). render() fetch() componentDidMount() My testing code is similar to this: describe('MyComponent', () => { fetchMock.get('*', some_response); it('renders something', () => {...

Jest fake timers with promises

Jest fake timers with promises I'm having a little trouble getting the Jest testing framework (version 23.2.0) to work nicely when using a combination of fake timers and promises. Where am I going wrong? Let's say I have the following module: // timing.js export const timeout = ms => new Promise(resolve => { setTimeout(resolve, ms) }) And my test file looks like: // timing.test.js import { timeout } from './timing' describe('timeout()', () => { beforeEach(() => { jest.useFakeTimers() }) it('resolves in a given amount of time', () => { const spy = jest.fn() timeout(100).then(spy) expect(spy).not.toHaveBeenCalled() jest.advanceTimersByTime(100) expect(spy).toHaveBeenCalled() }) }) This fails with the following output: ● timeout › resolves in a given amount of time expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called, but it was not called. 15 | 16 | jest.advanceTimers...