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

如何使用节点获取,超级测试和打字稿设置获取模拟

运维笔记admin9浏览0评论

如何使用节点获取,超级测试和打字稿设置获取模拟

如何使用节点获取,超级测试和打字稿设置获取模拟

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

到目前为止,我的解决方案在下面,但路由器中的访存未将模拟访存设置与访存模拟一起使用。单元测试失败,因为未返回我模拟的预期响应。我尝试按照documentation进行全局提取模拟,但是没有成功,打字稿很难遵循我发现的非打字稿解决方案。如果可能的话,我想避免使用非全局沙箱,因为我不得不重新编写很多代码来传递获取。

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('', expectedResponse);

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

server.ts

import * as Koa from 'koa';
import * as Router from 'koa-router';
import fetch from 'node-fetch';

const app = new Koa();

const router = new Router();

router.get('/test', async (ctx) => {
  const options = { method: 'GET' };
  try {
        const response = await fetch('', options);
        ctx.body = await response.json();
  } catch (error) {
      error.fetchUrl = url;
      throw error;
  }
});

app.use(router.routes());

const server = app.listen(3000);

export default server;
回答如下:
发布评论

评论列表(0)

  1. 暂无评论