How to test async actions that returns promise?

两盒软妹~` 提交于 2021-01-29 22:07:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!