You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Nock仅Mock同一主机下的特定路径请求?

Fixing Nock to Mock Only Dynamic /account/{id} Routes (With allowUnmocked Working)

Hey there! Let's sort out your Nock problem: you want to mock only requests like http://blabla.com/account/123456 or http://blabla.com/account/999999 (with dynamic unknown IDs) while letting other requests to the same host hit the real API. And even though you set allowUnmocked: true, it's not behaving as expected. I've dealt with this exact scenario before—here's how to make it work:

1. Use Regex for Dynamic Path Matching

First, target the http://blabla.com host and use a regular expression to match any numeric ID in the /account path. This ensures all dynamic ID variations get caught by your mock:

const nock = require('nock');

// Mock any /account/{numeric-id} request
const accountMock = nock('http://blabla.com')
  .get(/^\/account\/\d+$/) // Regex matches paths like /account/123456 or /account/999999
  .reply(200, (uri) => {
    // Extract the ID from the request URI to make the mock response dynamic
    const accountId = uri.split('/').pop();
    return {
      id: accountId,
      status: 'mocked',
      data: { name: 'Mocked Account', balance: 1000 }
    };
  });

2. Ensure allowUnmocked Is Configured Correctly

The allowUnmocked: true setting isn't working for you probably because it's not applied in the right place. There are two reliable ways to set it:

Option 1: Global Default (Applies to All Nock Scopes)

Set this once at the top of your test file or setup script to let all unmocked requests on any host go through:

nock.defaults({ allowUnmocked: true });

Option 2: Per-Scope Configuration (Only for This Host)

If you only want unmocked requests allowed for http://blabla.com, set it directly when creating the scope:

const scope = nock('http://blabla.com', { allowUnmocked: true })
  .get(/^\/account\/\d+$/)
  .reply(200, { /* Your mock response */ });

Pro Tip: If you have existing Nock scopes for the same host, make sure this configuration takes precedence—global defaults apply to all scopes created after setting them.

3. Troubleshoot Common Pitfalls

  • Check HTTP Method Matching: If your real request uses POST instead of GET, your mock needs to use .post() instead of .get(). Mismatched methods mean the mock won't trigger, and if allowUnmocked is off, you'll get an error.
  • Case Sensitivity: Nock matches paths strictly by default. If your request uses /Account/123 (capital A) but your mock uses /account/123, add { ignorePathCase: true } to your scope config to fix this.
  • Avoid Unnecessary .persist(): Using .persist() makes your mock stay active indefinitely, which might interfere with other tests. Only use it if you need the mock to work for multiple requests to the same path.

4. Verify It Works

Test two scenarios to confirm:

  1. Send a request to http://blabla.com/account/123456—it should return your mocked response.
  2. Send a request to another path like http://blabla.com/profile—it should hit the real API instead of being blocked.

内容的提问来源于stack exchange,提问作者Damian Paypal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:23:05