使用mockttp库模拟HTTP服务器和客户端进行单元测试

简介

mockttp 是一个用于在 Node.js 中模拟 HTTP 服务器和客户端的库。它可以帮助我们进行单元测试和集成测试,而不需要实际发送 HTTP 请求。

安装

shell 复制代码
npm install mockttp @types/mockttp

模拟http服务测试

首先导入并创建一个本地服务器实例

typescript 复制代码
import { getLocal } from 'mockttp';
const mockServer = getLocal();

在测试前需要启动服务

typescript 复制代码
mockServer.start(8080);

然后通过mockServer的forGet方法模拟一个GET请求,并设置响应状态码和响应体,这里其实就是我们期望模拟的请求和返回码与内容

typescript 复制代码
await mockServer
  .forGet('/my-mocked-path')
  .thenReply(200, '{"message": "ok"}');

接下来使用fetch方法发送一个请求,然后断言返回的内容是否是我们期望的

typescript 复制代码
const response = await fetch(
  `http://localhost:${mockServer.port}/my-mocked-path`,
);
expect(await response.text()).toEqual('{"message": "ok"}');

最后停止服务

typescript 复制代码
mockServer.stop()

最后,看一个完整的测试例子

my.spec.ts

typescript 复制代码
import { getLocal } from 'mockttp';

const mockServer = getLocal();

describe('Mockttp test', () => {
  beforeEach(() => mockServer.start(8080));
  afterEach(() => mockServer.stop());

  it('test get', async () => {
    await mockServer
      .forGet('/my-mocked-path')
      .thenReply(200, '{"message": "ok"}');

    const response = await fetch(
      `http://localhost:${mockServer.port}/my-mocked-path`,
    );

    expect(await response.text()).toEqual('{"message": "ok"}');
  });

  it('test post', async () => {
    await mockServer
      .forPost('/my-mocked-path')
      .withBody(JSON.stringify({ key: 'value' }))
      .thenReply(200, '{"message": "ok"}');

    const response = await fetch(
      `http://localhost:${mockServer.port}/my-mocked-path`,
      {
        method: 'POST',
        body: JSON.stringify({ key: 'value' }),
      },
    );

    expect(await response.text()).toEqual('{"message": "ok"}');
  });
});
相关推荐
贩卖纯净水.4 小时前
Webpack的基本使用 - babel
前端·webpack·node.js
贩卖纯净水.6 小时前
Webpack依赖
前端·webpack·node.js
笑醉踏歌行8 小时前
NVM,Node.Js 管理工具
运维·ubuntu·node.js
chxii10 小时前
1.4 Node.js 的 TCP 和 UDP
node.js
xd000021 天前
11. vue pinia 和react redux、jotai对比
node.js
程序猿小D1 天前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
AI+程序员在路上1 天前
单元测试与QTestLib框架使用
开发语言·c++·单元测试
前端老六喔1 天前
🎉 开源项目推荐 | 让你的 TypeScript/React 项目瘦身更简单!
node.js·前端工程化
醉书生ꦿ℘゜এ1 天前
npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
超级土豆粉1 天前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js