问题
fetchMock.get(`http://localhost:8080/data/v1/shopping-cart.json#/`).then(res => {
console.log('response ', res);
});
I am passing http://localhost:8080/data/v1/shopping-cart.json#/
as a base URL to the fetchMock.get() method and getting the following output:
fetch-mock: Invalid parameters passed to fetch-mock
What could be a reason?
回答1:
First, you actually misuse fetchMock()
. Check their docs on details. It's expected you to pass url and callback as part of .get()
:
fetchMock.get('http://localhost:8080/data/v1/shopping-cart.json', (url, opts) => {
return {body: 'aaa', status: 200}
});
fetch('http://localhost:8080/data/v1/shopping-cart.json').then(res => console.log(res));
Second you should not use hash part(#/
in your case) for URL mocked. Browser does not send this part to server so I believe your mock may not work at all(until fetch-mock
strips this part for mocks under the hood, but I'd not rely on that).
回答2:
You can mock the fetch method to return mock promise, as below:
in your test case:
window.fetch = jest.fn().mockImplementation(() =>
new Promise((resolve) =>
resolve({ /** dummy response object here */ })
)
);
and then when you call the action with async calls, the result should be equal to what you were doing in the then
handler (success handler)
similarly, you can reject
the promise to test the catch
handler.
Hope it helps.
来源:https://stackoverflow.com/questions/57196162/how-to-test-async-actions-that-returns-promise