我试图在单元测试中模拟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:不允许net connect for “127.0.0.1:54877/auth/register”
答案 0 :(得分:0)
看看nock documentation。 nock.disableNetConnect
阻止真正的http请求发生,看起来您尝试nock的端点正在端口54877上的服务器上运行,但您似乎正在尝试阻止在端口5000上运行的服务器。