Source:  Twitter logo

I want to write a test which mocks a promise in reactjs

I just need a mocked implementation of getHeaders() to return a string

export const loadAllProjects = () => {
    return (dispatch) => {
        getHeaders()
            .then(headers => {
                ...do stuff
            })
    }
}

to clarify my original function was...

export const loadAllProjects = () => {
    return (dispatch) => {
                ...do stuff
    }
}

...and my test was...

    it('should create SET_ALL_PROJECTS action when fetching projects', () => {
    fetchMock
        .getOnce('http://test.projects.api/api/projects',
        {
            body: [{name: "x"}],
            headers: { 'content-type': 'application/json' }
        }).spy()
    const expectedActions = [
        { type: "SET_ALL_PROJECTS", json: [{name:"x"}] },
    ]
    checkAsyncActionsWereDispatched(expectedActions, actions.loadAllProjects)
});

I want the test to work with the mocked header

const getHeaders = () => {
    return new Promise((resolve, reject) => {
        resolve("some string");
    });
};

a = await getHeaders();    //some string
7 users liked answer #0dislike answer #07
Ronn Wilder profile pic
Ronn Wilder

Use Promise.resolve

return Promise.resolve("your headers here");
1 users liked answer #1dislike answer #11
Nicholas Yang profile pic
Nicholas Yang

You can use jest to mock a promise for testing

Example for the eventual completion:

const mockPostSpy = jest
.spyOn(axios, 'post')
.mockImplementation(() => {
    return new Promise((resolve) => {
        return resolve({
            data: {},
        });
    });
});

Example for the operation failed:

const mockPostSpy = jest
.spyOn(axios, 'post')
.mockImplementation(() => {
    return new Promise((resolve) => {
        return reject({});
    });
});

Good luck to you ^^

0 users liked answer #2dislike answer #20
Hieu Dang profile pic
Hieu Dang

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).