0

あるコンポーネントで、xhr リクエストを「/api/somecall」に送信しました

MochaJS を使用してテスト目的で HTTP リクエストをモックしようとしています。

nock に入りましたが、最初のパラメーターはドメインです。複数のドメインで同じアプリを使用しているため、これを修正できません。

私は location.href で DOM をモックして、xhr がこのように Mocha のテスト セッションの開始時にヘルパーで特定のドメインに送信されるようにしました (このコードの一部を Web で見つけました)。

// setup the simplest document possible
var doc = jsdom.jsdom('<!doctype html><html><body></body></html>', {url: "http://localhost"})

// get the window object out of the document
var win = doc.defaultView

// set globals for mocha that make access to document and window feel 
// natural in the test environment
global.document = doc
global.window = win

// take all properties of the window object and also attach it to the 
// mocha global object
propagateToGlobal(win)

// from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
function propagateToGlobal (window) {
  for (let key in window) {
    if (!window.hasOwnProperty(key)) continue
    if (key in global) continue

    global[key] = window[key]
  }
}

残念ながら、後でこれを試してもうまくいきません:

nock('http://localhost')
      .get('/apv/v2/listings/' + county)
      .reply(200, responseData)

以前と同様に、すべてのテストでリクエストのタイムアウトが返されます。

どうすればそれを機能させることができますか?

4

1 に答える 1