【问题标题】:How to get the response from nock如何从 nock 获得响应
【发布时间】:2017-08-16 16:31:06
【问题描述】:

我一直在编写一些单元测试,但我注意到我似乎找不到测试异步函数的好方法。所以我找到了诺克。看起来很酷,只要它有效。我显然错过了一些东西......

import nock from 'nock';
import request from 'request';

const profile = {
    name: 'John',
    age: 25
};

const scope = nock('https://mydomainname.local')
    .post('/api/send-profile', profile)
    .reply(200, {status:200});

request('https://mydomainname.local/api/send-profile').on('response', function(request) {
    console.log(typeof request.statusCode); // this never hits
    expect(request.statusCode).to.equal.(200);
});

request 永远不会发生,那么我如何测试 nock 是否真的返回了{status:200}?我也试过fetch 和常规的http 电话。这让我觉得这与我的诺克代码有关?提前感谢您的帮助!

【问题讨论】:

    标签: javascript unit-testing http nock


    【解决方案1】:

    Nock 不返回 {status:200},因为它正在拦截 POST 请求,但 request 语句正在发送 GET 请求。

    您似乎想拦截带有指定profilePOST 请求?代码是:

    var nock = require('nock');
    var request = require('request');
    
    const profile = {
      name: 'John',
      age: 25
    };
    
    const scope = nock('https://mydomainname.local')
      .post('/api/send-profile', profile)
      .reply(200, {status:200});
    
    request.post('https://mydomainname.local/api/send-profile', {json: {name: 'John', age: 25}}).on('response', function(request) {
      console.log(request.statusCode); // 200
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      相关资源
      最近更新 更多