Jest - Clean up a function called inside a React component

Jest provides a way to mock the features described in their docs

apiGetMethod = jest.fn().mockImplementation(
    new Promise((resolve, reject) => {
        const userID = parseInt(url.substr('/users/'.length), 10);
        process.nextTick(
            () => users[userID] ? resolve(users[userID]) : reject({
                error: 'User with ' + userID + ' not found.',
            });
        );
    });
);

However, this bullying seems to work only when the function is called directly in the test.

describe('example test', () => {
    it('uses the mocked function', () => {
        apiGetMethod().then(...);
    });
});

If I have a React component defined as such, how can I make fun of it?

import { apiGetMethod } from './api';

class Foo extends React.Component {
    state = {
        data: []
    }

    makeRequest = () => {
       apiGetMethod().then(result => {
           this.setState({data: result});
       });
    };

    componentDidMount() {
        this.makeRequest();
    }

    render() {
        return (
           <ul>
             { this.state.data.map((data) => <li>{data}</li>) }
           </ul>
        )   
    }
}

I have no idea how to do this, so the component Foocalls my mock implementation apiGetMethod()so that I can verify that it displays the data correctly.

(this is a simplified, far-fetched example for understanding how to simulate functions called inside react components)

edit: api.js file for clarity

// api.js
import 'whatwg-fetch';

export function apiGetMethod() {
   return fetch(url, {...});
}
+4
2

./api ,

import { apiGetMethod } from './api'

jest.mock('./api', () => ({ apiGetMethod: jest.fn() }))

, mockImplementation:

apiGetMethod.mockImplementation(() => Promise.resolve('test1234'))
+5

jest.mock @Andreas . .

const api = require('./api');
api.apiGetMethod = jest.fn(/* Add custom implementation here.*/);

apiGetMethod Foo.

+4

Source: https://habr.com/ru/post/1675188/


All Articles