Javascript 如何从nock获得响应

Javascript 如何从nock获得响应,javascript,unit-testing,http,nock,Javascript,Unit Testing,Http,Nock,我一直在写一些单元测试,我注意到我似乎找不到一个测试异步函数的好方法。所以我找到了诺克。它看起来很酷,只要它起作用。我显然错过了一些东西 import nock from 'nock'; import request from 'request'; const profile = { name: 'John', age: 25 }; const scope = nock('https://mydomainname.local') .post('/api/send-pr

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

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
调用。这让我觉得这和我的nock代码有关?提前感谢您的帮助

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

您似乎想要截获具有指定的
配置文件的
POST
请求?守则是:

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
});