[Unit Testing] Mock an HTTP request using Nock while unit testing
HTTP Using an request while Testing unit mock
2023-09-14 08:59:17 时间
When testing functions that make HTTP requests, it's not preferable for those requests to actually run. Using the nock
JavaScript library, we can mock out HTTP requests so that they don't actually happen, control the responses from those requests, and assert when requests are made.
const assert = require('assert'); const nock = require('nock'); require('isomorphic-fetch'); function getData() { return fetch('https://jsonplaceholder.typicode.com/users') .then(response => response.json()); } describe('getData', () => { it('should fetch data', () => { const request = nock('https://jsonplaceholder.typicode.com') .get('/users') .reply(200, [{username: 'joe'}]); getData() .then(response => { assert.deepEqual(response, [{username: 'joe'}]); assert.ok(request.isDone()); }); }); })
相关文章
- 经典面试题 HTTPS和HTTP有什么区别?[通俗易懂]
- Node.js中Http模块
- Request Smuggling Via HTTP/2 Cleartext
- 格式化http的header字符串为数组(格式为键值对或格式传header值用的索引数组)
- 【Flutter】HTTP 网络操作 ( 引入 http 插件 | 测试网站 | Get 请求 | Post 请求 | 将响应结果转为 Dart 对象 | Future 异步调用 )
- Python模拟http get详解编程语言
- Linux下使用HTTP代理的技术指南(linuxhttp代理)
- 端口Linux查看HTTP端口:一步一步指南(linux查看http)
- 服务器Linux下简易配置HTTP服务器(linux配置http)
- 使用 gorilla/mux 进行 HTTP 请求路由和验证
- 深入浅出Mongodb Http: 开箱即用的可扩展性数据库(mongodb http)
- Linux下快速访问HTTP(linux 访问http)
- 如何使用Linux搭建一个安全的HTTP服务器(linux搭建http服务器)
- 一步之遥从HTTP访问Oracle数据库(http访问oracle)
- aspHttp_Referer,Server_Name和Http_Host
- Python中用pycurl监控http响应时间脚本分享