标签: fetch-mock

如何使用 node-fetch、supertest 和 typescript 设置 fetch-mock

我正在尝试向我的节点 typescipt 项目添加一些笑话测试。我想使用 supertest 来调用我的 koa 路由器,但也使用 fetch-mock 来模拟使用 node-fetch 发出的请求。

到目前为止,我的解决方案如下,但我的路由器中的提取不使用带有 fetch-mock 的模拟提取设置。单元测试失败,因为我嘲笑的预期响应没有返回。我曾尝试遵循global fetch mocking的文档但没有成功,并且 typescript 使我很难遵循我找到的非 typescript 解决方案。如果可能,我想避免使用非全局沙箱,因为我必须重新编写大量代码来传递获取。

server.spec.ts

import * as fetchMock from 'fetch-mock';
import * as request from 'supertest';
import server from './server';

afterEach(() => {
  server.close();
  fetchMock.reset();
});

describe('router', () => {
  test('GET: should return data', async () => {
    const expectedResponse = { test: 'TEST' };
    fetchMock.get('https://myapi.com/test', expectedResponse);

    const response = await request(server).get('/test');
    expect(response.status).toEqual(200);
    expect(response.body).toMatchObject(expectedResponse);
  });
});
Run Code Online (Sandbox Code Playgroud)

服务器.ts

import * as fetchMock …
Run Code Online (Sandbox Code Playgroud)

unit-testing node.js typescript jestjs fetch-mock

7
推荐指数
1
解决办法
8260
查看次数

fetch-mock不模拟我的提取

这是代码片段:

var fetch = require("node-fetch");
var fetchMock = require("fetch-mock");

function setupMockBlockChainExplorer() {
  fetchMock.mock("https://cardanoexplorer.com/api/addresses/summary/DdzFFzCqrhsmagp4fDZpcY9UaBJk4Z8GaDfxqMCSwxPs3PnVoXmJWUZcgAxw3diCHVYauontEfk7YGeAu2LvAwq3aG2XQ8Mtsz7Vc8LA", {
    "status" : 200,
    "body" : "override"
  });
}

async function makeRequest(url, method = "get", body = null, headers = null) {
  const res = await fetch(url, {
    method: method,
    headers: headers,
    body: body,
  });

  return res.json()
};

setupMockBlockChainExplorer();

var req = makeRequest("https://cardanoexplorer.com/api/addresses/summary/DdzFFzCqrhsmagp4fDZpcY9UaBJk4Z8GaDfxqMCSwxPs3PnVoXmJWUZcgAxw3diCHVYauontEfk7YGeAu2LvAwq3aG2XQ8Mtsz7Vc8LA");

// I would expect it to print "override" but it prints the http response from the real request instead
req.then(console.log)
Run Code Online (Sandbox Code Playgroud)

因此,正如您在上面的代码中看到的那样,我试图覆盖HTTP请求,但是我仍然使用fetch来访问真实的URL。我已经阅读了fetch-mock文档(http://www.wheresrhys.co.uk/fetch-mock/installation.html),并且还尝试过这样的配置:

fetchMock.config …
Run Code Online (Sandbox Code Playgroud)

fetch node.js fetch-mock

6
推荐指数
1
解决办法
3295
查看次数

使用 Fetch-Mock 返回测试 Blob

我有一个从服务器接收文件的提取,我试图用fetch-mock.
使用此代码,我可以模拟端点并将 blob 放入正文中:

const blob = new Blob(['a', 'b', 'c', 'd']);
fetchMock.once('*', {body: blob}, {sendAsJson: false});
Run Code Online (Sandbox Code Playgroud)

正在测试的代码是:

fetch(url).then( ( response ) => {
            console.log(response);
            return response.blob();
        } ).then( ( blob ) => {
            console.log(blob);
        } )
Run Code Online (Sandbox Code Playgroud)

我可以看到 Blob 在请求的正文中

Body {
    url: '/mock/url',
    status: 200,
    statusText: 'OK',
    headers: Headers { _headers: {} },
    ok: true,
    body: Blob {},
    bodyUsed: false,
    size: 0,
    timeout: 0,
    _raw: [],
    _abort: false }
Run Code Online (Sandbox Code Playgroud)

但是运行测试会抛出错误:

    TypeError: response.blob is not a function
Run Code Online (Sandbox Code Playgroud)

使用服务器运行代码将一个有效的 …

javascript fetch-mock

6
推荐指数
1
解决办法
2398
查看次数

为什么 fetchmock restore 提供无与伦比的获取?

我已经根据已经定义的测试用例编写了逻辑。基本上,下面对一个服务器调用的 tc 检查是代码。如何修改我的逻辑以使 tc 通过?

这是测试用例:

it('there shall be only one server call in addFavourites()', (done) => {
        fetchMock.get('http://localhost:3000/movies', moviesTestData);
        fetchMock.get('http://localhost:3000/favourites', favouritesTestData);

        script.getMovies()
        .then(() => {
            return script.getFavourites();
        })
        .then(() => {
            fetchMock.restore();
            fetchMock.post('http://localhost:3000/favourites', moviesTestData[1]);
            return script.addFavourite(27621);
        })
        .then(() => {
             expect(fetchMock.done()).to.equal(true);
             done();
        })
        .catch((err) => {
            expect(err).to.equal(null, err);
            done();
        });
});
Run Code Online (Sandbox Code Playgroud)

这是编写的逻辑。它基本上调用电影,尝试获取它,检查所选的收藏夹是否存在,如果不存在则添加

function addFavourite(event) {
    const id = event;
    // eslint-disable-next-line consistent-this
    // const self = this;
    let favmovie = {};
    let favmovies={};
    //     let favmovie = {};
     return …
Run Code Online (Sandbox Code Playgroud)

javascript fetch karma-mocha fetch-api fetch-mock

6
推荐指数
0
解决办法
1518
查看次数

如何使用有效负载提取模拟发布请求

我正在使用 wheresrhys fetch-mock npm 模块在我的应用程序中运行功能测试。我想用“POST”方法和特定的有效负载来模拟一次提取。

它看起来像这样:

fetchMock.mock({
        routes: {
            name: 'LoginSuccess',
            matcher: "https://myurl",
            method: 'POST',
            payload: {
                params:{User: "ABCDE@gmail.com", Password: "password"}
            },
            response: {  
                result:{
                    message: "Successful login", 
                    credentials: "XXXXXXXXXXXXX"
                }
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

我想检查我的 fetch 的有效负载并相应地给出响应。例如,我可以模拟用户提交错误密码的一次登录,然后他们再次尝试并提交正确的信息并被授予访问权限。相同的 url,不同的负载,不同的响应。

是否有可能做到这一点?我知道可以检查获取的方法,但我想对有效载荷做同样的事情。

或者有没有更好的方法来做到这一点?

我还没有在模块的自述文件或fetch-mock 包的测试部分找到解决方案。

unit-testing functional-testing fetch fetch-mock

5
推荐指数
1
解决办法
8236
查看次数

如何为每个测试重置 fetch-mock?

我使用 Jest 和 进行了几个 React 测试fetch-mock,每个测试都执行一些 get 操作,所以我最初所做的是:

beforeAll(){
    fetchMock.get(`*`, JSON.stringify(CORRECTRESPONSE));
}
Run Code Online (Sandbox Code Playgroud)

但是,在某些测试中我需要返回错误的数据作为答案,例如:

test('Wrong get answer', ()=> {
   fetchMock.get('*', JSON.stringify(WRONGRESPONSE), {overwriteRoutes: true});
}));
Run Code Online (Sandbox Code Playgroud)

因此,由于我需要重置以下测试的响应(因此 return CORRECTRESPONSE,我想出了这个解决方案:

beforeEach(){
    fetchMock.get(`*`, JSON.stringify(CORRECTRESPONSE));
}

afterEach(fetchMock.restore);
Run Code Online (Sandbox Code Playgroud)

有更好的办法吗?

unit-testing fetch reactjs jestjs fetch-mock

5
推荐指数
1
解决办法
8892
查看次数

类型错误:无法设置只有 getter 的 #<Window> 属性 localStorage

我在像这样的unitests中嘲笑localStorage

function storageMock() {
    var storage = {};
    ....
}
Run Code Online (Sandbox Code Playgroud)

并设置 localStorage 像

window.localStorage = localStorageMock()
Run Code Online (Sandbox Code Playgroud)

它工作正常,直到我将 Node 更新为10.15.1.

这是抛出错误TypeError: Cannot set property localStorage of #<Window> which has only a getter

知道如何模拟 localStorage 并将其设置为 window.localStorage 。

PS 我在 localStorage 上得到了类似的答案setItemgetItem有什么方法可以一次性设置整个 localStorage 吗?

javascript local-storage fetch-mock

5
推荐指数
1
解决办法
1万
查看次数

如何模拟几个获取fetch-mock?

我正在测试我的反应组件,我想模拟几个get操作.我想做的是:

test(`Created correctly`, async () => {
    fetchMock.get(`*`, JSON.stringify(FIRSTGETOBJ));
    fetchMock.get(`*`, JSON.stringify(SECONDGETOBJ));
    fetchMock.get(`*`, JSON.stringify(THIRDGETOBJ));

    //...
}
Run Code Online (Sandbox Code Playgroud)

每个的URL都get相同,但有效负载会发生变化.但是,使用上面的代码我会得到:

Error: Adding route with same name as existing route. See `overwriteRoutes` option.
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

unit-testing mocking fetch fetch-mock

4
推荐指数
1
解决办法
3156
查看次数

fetch-mock:没有为 POST 定义回退响应

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

控制台警告 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 …
Run Code Online (Sandbox Code Playgroud)

javascript api unit-testing jestjs fetch-mock

4
推荐指数
2
解决办法
5396
查看次数

提取模拟所有请求

我正在使用fetch-mock来模拟对服务器的一些请求。这是所有请求的发出地:

import fetchMock from 'fetch-mock'
import initialState from 'src/initial-state'

if (process.env.NODE_ENV === 'development') {
  fetchMock.post('/some/endpoint', initialState.entities.multichannelEngagement)
}
Run Code Online (Sandbox Code Playgroud)

但是,不仅此端点是模拟的,而且所有同构提取的请求

import 'isomorphic-fetch'
export function makeRequest(endpoint, config = {}) {
  return window.fetch(endpoint, config)
  .then(response => {
    return response.json()
  .then(json => ({ json, response }))
  .catch(() => ({ response }))
})
.then(({ json, response }) => {
  if (!response.ok) {
    throw json ? json : new Error(response.statusText)
  } else {
    return json
  }
})
.catch((e) => {
  return Promise.reject(e)
})
Run Code Online (Sandbox Code Playgroud)

}

我的webpack.config.js如下:

import path …
Run Code Online (Sandbox Code Playgroud)

mocking fetch reactjs webpack fetch-mock

1
推荐指数
1
解决办法
1万
查看次数