[Unit Testing] Mock an HTTP request using Nock while unit testing

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());
            });
    });
})
复制代码

 

posted @   Zhentiw  阅读(189)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2015-10-20 [AngularJS] Enable Animations Explicitly For A Performance Boost In AngularJS
2015-10-20 [AngularJS + Unit Testing] Testing Directive's controller with bindToController, controllerAs and isolate scope
点击右上角即可分享
微信分享提示