最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Nock (npm): FetchError: request to <url> failed, reason: Nock: No match for request - Stack Overflow

programmeradmin0浏览0评论

My intention is to write a test, anticipate a certain API is called as specified and fail if not. For example if a header is missing or the query is different. I want it to fail fast.

import { createTestApp, TestApplication } from '../_core/application';
import nock from 'nock';

describe('Nock', () => {
  let app: TestApplication;

  beforeAll(async () => {
    app = await createTestApp();
  });


  it('Calls HTTP endpoint', async () => {
    const scope = nock('').get('/todos/2').reply(200, {
      userId: 23,
    });

    const response = await app.httpClient.request('/testing', {
      method: 'GET',
    });

    expect(response.status).toBe(200);
    expect(scope.isDone()).toBe(true);
  });
});

I have this error:

FetchError: request to  failed, reason: Nock: No match for request {
      "method": "GET",
      "url": ";,
      "headers": {
        "accept": [
          "*/*"
        ],
        "user-agent": [
          "node-fetch/1.0 (+)"
        ],
        "accept-encoding": [
          "gzip,deflate"
        ]
      }
    }
    at OverriddenClientRequest.<anonymous> (node_modules/node-fetch/lib/index.js:1501:11)
      at Socket.<anonymous> (node_modules/propagate/index.js:64:17)
      at node_modules/nock/lib/socket.js:101:14

thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout, if this is a long-running test. See ."

      14 |   });
      15 |
    > 16 |   it('Calls HTTP endpoint', async () => {
         |   ^
      17 |     const scope = nock('').get('/todos/2').reply(200, {
      18 |       userId: 23,
      19 |       id: 1,

      at test/graphql/graphql.spec.ts:16:3
      at Object.<anonymous> (test/graphql/graphql.spec.ts:4:1)

As you can see the API was called with /todos/1 instead of /todos/2

The issue I have is why it didn't fail fast, shortly after my call to:

await app.httpClient.request('/testing', {
      method: 'GET',
    });

Because this resolves quickly in practice.

Also, when I nock a different base url, this works perfectly, for example:

The assertion fails quickly. For additional context:

this call app.httpClient.request calls my rest api with node-fetch and that rest api calls with node-fetch jsonplaceholder.typicode

What do I not understand here? Can I set this up differently ?

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论