5

我所有的GET请求都在通过,但POST请求失败。当我fetch-mock7.3.0to7.3.1更高版本更新时会发生这种情况。

控制台警告 Unmatched POST to url

错误 fetch-mock: No fallback response defined for POST to url

http.js

export const get = (url) => {
  const options = {
    method: 'GET',
    credentials: 'same-origin'
  };

  return fetch(url, options).then(handleJsonResponse);
};

export const post = (url, body) => {
  const headers = {
    'content-type': 'application/json',
    'pragma': 'no-cache',
    'cache-control': 'no-cache'
  };

  return fetch(url, {
    credentials: 'same-origin',
    method: 'POST',
    cache: 'no-cache',
    body: JSON.stringify(body),
    headers
  }).then(handleJsonResponse);
};

http.spec.js

const url = '/path/to/url'

describe('get', () => {
    it('makes a GET request', async () => {
      fetchMock.mock({
        name: 'route',
        matcher: url,
        method: 'GET',
        credentials: 'same-origin',
        response: {
          status: 200,
          body: []
        }
      });

      const response = await get(url);

      expect(fetchMock.called()).toEqual(true);
      expect(fetchMock.calls().length).toEqual(1);
      expect(fetchMock.calls('route').length).toEqual(1);
      expect(response).toEqual([]);
    });
  });

  describe('post', () => {
    const requestBody = {request: 'request'};

    it('makes a POST request', async () => {
      fetchMock.mock({
        name: 'route',
        matcher: url,
        method: 'POST',
        credentials: 'same-origin',
        cache: 'no-cache',
        body: JSON.stringify(requestBody),
        headers: {
          'content-type': 'application/json',
          'pragma': 'no-cache',
          'cache-control': 'no-cache'
        },
        response: {
          status: 200,
          body: []
        }
      });

      const response = await post(url, requestBody);

      expect(fetchMock.called()).toEqual(true);
      expect(fetchMock.calls().length).toEqual(1);
      expect(fetchMock.calls('route').length).toEqual(1);
      expect(fetchMock.lastOptions().headers).toEqual({
        'content-type': 'application/json',
        'pragma': 'no-cache',
        'cache-control': 'no-cache'
      });
      expect(response).toEqual([]);
    });
  });

关于是什么原因造成的任何想法?有没有办法获得更有意义的日志来帮助调试?

我宁愿不去尝试nockjest-fetch-mock的替代路径。

4

2 回答 2

7

好吧,在对图书馆本身进行了数小时的研究之后,我发现了问题所在。

在我的代码(和上面的代码段)中,我正在对 body进行字符串化JSON.stringify(body)。图书馆generate-matcher.js正在解析JSON.parse(body),然后比较两者 - 导致失败的点。我现在只是将它作为原始对象发送。

于 2020-01-10T10:49:32.313 回答
0

万一其他人将来在这里结束,我会遇到同样的错误fetch-mock unmatched get

我看到对这个问题的响应提交给 fetch-mock,这促使我仔细检查了我的预期值和模拟值。

事实证明,我的问题与所描述的错误完全一样,我期望的模拟路由和被调用的实际路由由于拼写错误而不匹配。

于 2021-03-12T00:46:41.397 回答