首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >节点+测试:如何使用nock模拟api

节点+测试:如何使用nock模拟api
EN

Stack Overflow用户
提问于 2017-05-17 17:27:12
回答 2查看 5.4K关注 0票数 3

我试图在单元测试中模拟api,如下所示:

代码语言:javascript
复制
const request = require('supertest');
const nock = require('nock');
const app = require('../app');

const agent = request.agent(app);
nock.disableNetConnect();
const userResponse = {
    user: {
      _id: '58828157ce4e140820e23648',
      info: {
        email: 'fake@test.io',
        password: '1',
        name: 'testx',
      },
};
  it('should register new user', (done) => {
    nock('http://localhost:5000')
      .post('/auth/register')
      .reply(200, userResponse);



    agent.post('/auth/register')
      .send({
        name: 'test',
        email: 'fake@test.io',
        password: '1',
      })
      .expect(200)
      .end((error, response) => {
        expect(response.body.user.info.email).to.equal('fake@test.io');
        expect(response.body.user.info.name).to.equal('test');
        done();
      });
  }).timeout(5000);

但是我发现了这个错误:

NetConnectNotAllowedError: Nock:不允许“127.0.0.1:54877/auth/寄存器”的网络连接

EN

回答 2

Stack Overflow用户

发布于 2017-07-27 10:49:44

看看nock文档nock.disableNetConnect可以防止真正的http请求发生,而且您要尝试的端点似乎正在端口54877上的服务器上运行,但您似乎试图对运行在端口5000上的服务器进行锁定。

票数 0
EN

Stack Overflow用户

发布于 2022-07-05 14:10:58

如果您希望允许请求访问某个域的internet,您可以:

代码语言:javascript
复制
const unBlockedDomains = ['toto.com', 'tata.fr'];
nock.enableNetConnect(host =>
  Boolean(unBlockedDomains.find(domain => host.includes(domain))),
);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44031342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档