如何在 ReactJS 中模拟 Promise?

Tin*_*ino 2 reactjs jestjs

我想编写一个测试来模拟reactjs中的承诺

我只需要 getHeaders() 的模拟实现来返回一个字符串

export const loadAllProjects = () => {
    return (dispatch) => {
        getHeaders()
            .then(headers => {
                ...do stuff
            })
    }
}
Run Code Online (Sandbox Code Playgroud)

澄清我原来的职能是......

export const loadAllProjects = () => {
    return (dispatch) => {
                ...do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

...我的测试是...

    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)
});
Run Code Online (Sandbox Code Playgroud)

我希望测试能够使用模拟标头

Ron*_*der 8

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

a = await getHeaders();    //some string
Run Code Online (Sandbox Code Playgroud)