在reactjs中模拟一个函数

时间:2018-06-06 15:56:49

标签: javascript reactjs jestjs fetch-api

以前我有这样的功能。

export const loadProjects = () => {
    return (dispatch) => {
        const requestOptions = {
            method: 'GET',
            headers: {...},
        };
        return fetch(PROJECTS_API_URL + "/projects", requestOptions)
            .then(parseResponse)
            .then(json => dispatch(setAllProjects(json)))
            .catch(error => {
                dispatch(failedToLoadProjects(error))
            });
    }

我测试了这个

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"}] },
        ]
        checkActionsWereDispatched(expectedActions, actions.loadAllProjects)
    });

现在我已经更改了函数,因此它调用另一个函数来生成标题:

export const loadProjects = () => {
    return (dispatch) => {
        getHeaders()
            .then(myHeaders => {
                const requestOptions = {
                    method: 'GET',
                    headers: myHeaders,
                };
                return fetch(PROJECTS_API_URL + "/projects", requestOptions)
                    .then(parseResponse)
                    .then(json => dispatch(setAllProjects(json)))
                    .catch(error => {
                        dispatch(failedToLoadProjects(error))
                    });
            })
    }
 

我的问题是:如何更改测试以模拟getHeaders()函数返回的内容?

0 个答案:

没有答案