Node.js 如何使用chai、sinon和mocha模拟服务器响应
我最近写了一个小服务Node.js 如何使用chai、sinon和mocha模拟服务器响应,node.js,unit-testing,mocha.js,sinon,chai,Node.js,Unit Testing,Mocha.js,Sinon,Chai,我最近写了一个小服务 向包含服务定义的xml文件发出http请求 将响应的xml转换为json,并为给定键解析json 如果找到给定的键,则返回一个对象 否则将创建一个空数组 相关代码 this.\u makeResolveRequest返回一个承诺 _makeResolveRequest() { return new Promise(function (resolve, reject) { return request(options, function (error,
xml
转换为json
,并为给定键解析json
this.\u makeResolveRequest
返回一个承诺
_makeResolveRequest() {
return new Promise(function (resolve, reject) {
return request(options, function (error, response, body) {
if(error) {
reject(error);
}
resolve(body);
})
});
}
测试
现在我真的陷入了写测试的困境,我显然不知道从哪里开始
我想测试实际的实现,并验证链式方法在一起是否正常工作。因此,我的测试应该发出一个真正的http请求,但响应应该是模拟的。模拟响应应通过所有“站”。最后,我希望得到一个基于提供的模拟数据的对象
describe("Arguments", function () {
it("the service should be a string", function () {
expect(resolver.serviceType).to.be.a('string');
});
it("configuration should be a object", function () {
expect(resolver.options).to.be.a('object');
});
it("configuration should have a attribute protocol", function () {
expect(resolver.options).to.have.property('protocol');
});
it("configuration should have a attribute host", function () {
expect(resolver.options).to.have.property('host');
});
it("configuration have a attribute port", function () {
expect(resolver.options).to.have.property('port');
});
it('should use all passed options', function () {
// .catch() is used here as we do not have a server running
// which responds properly
resolver.resolve().catch(function (err) {
expect(err.options.uri).to.equal('http://localhost:1234/tr64desc.xml');
expect(err.options.uri).not.to.equal('https://localhost:1234/tr64desc.xml');
expect(err.options.uri).not.to.equal('https://localhost/tr64desc.xml');
expect(err.options.uri).not.to.equal('http://lorem.com/tr64desc.xml');
})
});
});
问题从这里开始
这显然会导致以下错误,因为没有运行响应请求的xml文件的服务器
{ [Error: connect ECONNREFUSED 127.0.0.1:1234]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 1234 }
您可以使用“”模拟服务器请求+响应(您可以设置应返回的响应代码和主体)
这里有更多教程:
希望有帮助 您可以使用“”模拟服务器请求+响应(您可以设置应返回的响应代码和正文)
这里有更多教程:
希望有帮助 是:)我刚才遇到了nock
是:)我刚才遇到了nock
是:)
describe("Service Resolver", function () {
let resolver = new ServiceResolver('CommonInterfaceService', {
protocol: 'http',
host: 'localhost',
port: '1234'
});
it('should return an object of CommonInterfaceService if the was available', function () {
resolver.resolve() //??
});
});
{ [Error: connect ECONNREFUSED 127.0.0.1:1234]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 1234 }