简体   繁体   English

无法使用 `fetch-mock-jest 1.5.1` 库模拟 fetch 调用

[英]cannot mock a fetch call with `fetch-mock-jest 1.5.1` lib

I'm trying to mock a fetch call using this fetch-mock-jest but it the code still trys to go to the remote address and eventually fail with error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: getaddrinfo ENOTFOUND some.domain.io] .我正在尝试使用此fetch-mock-jest模拟 fetch 调用,但代码仍然尝试转到远程地址并最终失败并显示错误消息FetchError: request to https://some.domain.io/app-config.yaml failed, reason: getaddrinfo ENOTFOUND some.domain.io]

Here the the test code这里是测试代码

import { AppConfig } from '@backstage/config';
import { loadConfig } from './loader';
import mockFs from 'mock-fs';
import fetchMock from 'fetch-mock-jest';

describe('loadConfig', () => {
  beforeEach(() => {
    fetchMock.mock({
      matcher: '*',
      response: `app:
          title: Example App
          sessionKey: 'abc123'
      `
    });
  });

  afterEach(() => {
    fetchMock.mockReset();
  });

  it('load config from remote path', async () => {
    const configUrl = 'https://some.domain.io/app-config.yaml';

    await expect(
       loadConfig({
        configRoot: '/root',
        configTargets: [{ url: configUrl }],
        env: 'production',
        remote: {
          reloadIntervalSeconds: 30,
        },
      })
    ).resolves.toEqual([
      {
        context: configUrl,
        data: {
          app: {
            title: 'Example App',
            sessionKey: 'abc123',
          },
        },
      },
    ]);
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  function defer<T>() {
    let resolve: (value: T) => void;
    const promise = new Promise<T>(_resolve => {
      resolve = _resolve;
    });
    return { promise, resolve: resolve! };
  }
});

loadConfig has the fetch code that I'm trying to mock. loadConfig有我试图模拟的提取代码。

export async function loadConfig(
  options: LoadConfigOptions,
): Promise<AppConfig[]> {
  const loadRemoteConfigFiles = async () => {
    const configs: AppConfig[] = [];

    const readConfigFromUrl = async (remoteConfigProp: RemoteConfigProp) => {
      const response = await fetch(remoteConfigProp.url);
      if (!response.ok) {
        throw new Error(
          `Could not read config file at ${remoteConfigProp.url}`,
        );
      }

      remoteConfigProp.oldETag = remoteConfigProp.newETag ?? undefined;
      remoteConfigProp.newETag =
        response.headers.get(HTTP_RESPONSE_HEADER_ETAG) ?? undefined;
      remoteConfigProp.content = await response.text();

      return remoteConfigProp;
    };

.......
    return configs;

}

let remoteConfigs: AppConfig[] = [];
  if (remote) {
    try {
      remoteConfigs = await loadRemoteConfigFiles();
    } catch (error) {
      throw new Error(`Failed to read remote configuration file, ${error}`);
    }
  }

........ do some stuff with config then return
return remoteConfigs;
}

The config is a yaml file, that eventually gets parsed and converted into config object.配置是一个 yaml 文件,最终会被解析并转换为配置对象。

Any idea why is it failing to mock the fetch call?知道为什么它无法模拟 fetch 调用吗?

replaced取代

import fetchMock from 'fetch-mock-jest';

with

const fetchMock = require('fetch-mock').sandbox();
const nodeFetch = require('node-fetch');
nodeFetch.default = fetchMock;

and fetchMock.mockReset();fetchMock.mockReset(); with fetchMock.restore();使用fetchMock.restore();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM