简介
mockttp 是一个用于在 Node.js 中模拟 HTTP 服务器和客户端的库。它可以帮助我们进行单元测试和集成测试,而不需要实际发送 HTTP 请求。
安装
npm install mockttp @types/mockttp
模拟http服务测试
首先导入并创建一个本地服务器实例
import { getLocal } from 'mockttp';
const mockServer = getLocal();
在测试前需要启动服务
mockServer.start(8080);
然后通过mockServer的forGet方法模拟一个GET请求,并设置响应状态码和响应体,这里其实就是我们期望模拟的请求和返回码与内容
await mockServer
.forGet('/my-mocked-path')
.thenReply(200, '{"message": "ok"}');
接下来使用fetch方法发送一个请求,然后断言返回的内容是否是我们期望的
const response = await fetch(
`http://localhost:${mockServer.port}/my-mocked-path`,
);
expect(await response.text()).toEqual('{"message": "ok"}');
最后停止服务
mockServer.stop()
最后,看一个完整的测试例子
my.spec.ts
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"}');
});
});