如何解决使用Got,Nock和Chai测试节点中的基本异步HTTP请求
我试图弄清楚为什么我的单元测试不能正常工作。尽管我使用Nock拦截了我的http请求,但似乎仍发出了外部网络请求。
我有一个非常基本的getUser
服务,getuser-got.js:
const got = require('got');
module.exports = {
getUser(user) {
return got(`https://api.github.com/users/${user}`)
.then(response=>JSON.parse(response.body))
.catch(error => console.log(error.response.body))
}
};
这可以成功调用,但是我要对其进行单元测试。
这是我的代码在名为getuser-got.test.js
的文件中:
const getUser = require('../getuser-got').getUser;
const expect = require('chai').expect;
const nock = require('nock');
const user_response = require('./response');
describe('GetUser-Got',() => {
beforeEach(() => {
nock('https//api.github.com')
.get('/users/octocat')
.reply(200,user_response);
});
it('Get a user by username',() => {
return getUser('octocat')
.then(user_response => {
// expect an object back
expect(typeof user_response).to.equal('object');
// test result of name and location for the response
expect(user_response.name).to.equal('The Octocat')
expect(user_response.location).to.equal('San Francisco')
})
});
});
名为response
的文件包含Github API预期响应的副本,我正在将其加载到user_response
变量中。我已经替换了name
和location
的值,以使测试失败。
module.exports = {
login: 'octocat',...
name: 'The FooBar',company: '@github',blog: 'https://github.blog',location: 'Ssjcbsjdhv',...
}
问题是我可以看到Nock没有拦截我的请求。当我运行测试时,它将继续对外部API进行实际调用。因此,测试通过了,因为它没有使用我的本地response
作为返回值。
我尝试添加nock.disableNetConnect();
,但这只会导致测试超时,因为它显然仍在尝试进行外部调用。如果我运行测试,我会得到:
➜ nock-tests npm test
> nock-tests@1.0.0 test /Users/corin/Projects/nock-tests
> mocha "test/test-getuser-got.js"
GetUser-Got
✓ Get a user by username (290ms)
1 passing (296ms)
没有Nock拦截我的http请求,我在做什么错了?
解决方法
传递给nock
函数的值不是有效的URL,它在模式中缺少冒号。
根据需要将其更新为nock('https://api.github.com')
会使测试在本地失败。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。