Nock is not intercepting API call in Redux test

不羁的心 提交于 2019-12-05 04:40:06

In order to use nock you must run your tests in node (using Jest or mocha), nock overrides node http behavior and for that reason it only works in node and not in browsers (like PhantomJS).

For example the link you pointed out is using Jest and first lines there are explicit about the node environment. Therefore, nock will work as a charm. http://redux.js.org/docs/recipes/WritingTests.html

Setting Up

We recommend Jest as the testing engine. Note that it runs in a Node environment, so you won't have access to the DOM.

As I see you can:

  • run your tests in a node environment
  • or use a different library to mock like fetch-mock

You need to pass just base URL to the main nock function and separate the URL path portion out into the .get() method.

nock('http://ws.audioscrobbler.com')
  .get('/2.0/')
  .query({
    method: 'artist.search',
    artist: 'bob',
    api_key: 'somekey123',
    format: 'json',
    limit: '5'
  })
  .reply(200, {fake: true})

I was able to get a fake response with the above code.

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