3

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

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: Not allow net connect for "127.0.0.1:54877/auth/register"

4

1 回答 1

0

查看nock 文档nock.disableNetConnect防止发生真正的 http 请求,并且您尝试连接的端点似乎正在端口 54877 上的服务器上运行,但您似乎正在尝试连接运行在端口 5000 上的服务器。

于 2017-07-27T10:49:44.073 回答