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

在Intern4与dojo中使用nock的正确方法

Using Nock with Intern 4 and a Non-dojoLoader Dojo Setup

Hey there! Let's walk through how to integrate nock smoothly with Intern 4, especially given your codebase's unique setup where core Dojo files aren't loaded via dojoLoader. Since you're already handling linting, builds, and most testing workflows, this should slot right into your existing toolchain.

First, Install Dependencies

Start by adding nock as a dev dependency if you haven't already:

npm install nock --save-dev

Basic Nock Setup in Intern Tests

Nock works by intercepting HTTP requests at the Node.js level, so it’s ideal for unit tests running in Node or Intern’s Node-based functional tests. Here’s how to structure your test files:

  1. Import nock and your Dojo modules
    Since you’re not using dojoLoader, you’ll want to require your Dojo request modules directly (adjust the path to match your project structure):

    const nock = require('nock');
    const assert = require('intern/chai!assert');
    const dojoXhr = require('../path/to/dojo/request/xhr'); // Your Dojo XHR module
    
  2. Manage Nock in Test Lifecycle Hooks
    Use Intern’s beforeEach and afterEach hooks to set up request intercepts and clean them up between tests—this prevents cross-test contamination:

    beforeEach(() => {
      // Intercept requests to your target API domain
      nock('https://your-api-domain.com')
        .get('/endpoint-you-test')
        .reply(200, { mockData: 'hello world' })
        .post('/submit-form')
        .reply(201, { success: true });
    });
    
    afterEach(() => {
      // Clear all active nock intercepts
      nock.cleanAll();
      // Optional: Verify all expected requests were made
      assert.isTrue(nock.isDone(), 'All mocked requests should have been triggered');
    });
    
  3. Write Tests with Mocked Responses
    Since Dojo’s requests are asynchronous, use async/await or return a Promise to let Intern handle the async flow:

    tests: {
      'fetch data with mocked API response': async () => {
        const response = await dojoXhr('https://your-api-domain.com/endpoint-you-test');
        assert.deepEqual(response.data, { mockData: 'hello world' }, 'Response should match mocked data');
      },
    
      'submit form and receive success': async () => {
        const response = await dojoXhr('https://your-api-domain.com/submit-form', {
          method: 'POST',
          data: { formField: 'value' }
        });
        assert.equal(response.data.success, true, 'Form submission should return success');
      }
    }
    

Handling Edge Cases for Your Non-dojoLoader Setup

  • Ensure Dojo modules resolve correctly: If your Dojo build outputs CommonJS modules, requiring them directly (as shown above) should work. If not, adjust your Intern config’s loaderOptions to map Dojo modules to their correct paths.
  • Browser-based functional tests note: Nock only works in Node.js. For browser-side tests, you’ll need a browser-compatible mocking tool like fetch-mock instead—since nock can’t intercept browser-level XHR/fetch requests.
  • Debugging uncaught requests: If nock isn’t intercepting a request, use nock.log(console.log) to see all incoming requests and verify your intercept URL/method matches exactly.

Quick Recap

  • Use Intern’s lifecycle hooks to create and clean up nock intercepts per test
  • Require Dojo modules directly (no dojoLoader needed) in your test files
  • Use async/await to handle Dojo’s asynchronous requests
  • For browser tests, swap nock for a browser-focused mocking tool

内容的提问来源于stack exchange,提问作者Chris Rymer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:57:12