Node.js 关于sinon在node js中的单元测试
这是我创建的类 如何使用sinon(stub和mock)为这个类编写单元测试,我必须只测试公共函数,这里唯一的公共函数是Node.js 关于sinon在node js中的单元测试,node.js,mocking,sinon,stub,Node.js,Mocking,Sinon,Stub,这是我创建的类 如何使用sinon(stub和mock)为这个类编写单元测试,我必须只测试公共函数,这里唯一的公共函数是getTenantId(Id),其中所有其他私有函数都有一个http请求,该请求可以给出有效响应或错误 有没有办法通过模仿所有其他私有函数来测试公共函数。我想预先定义每个私有函数将返回的数据以及它们从env获取并用于发送请求的主要数据。您可以使用nock()模拟所有http调用,并测试您通常会执行的公共函数 class FetchTenant { constructo
getTenantId(Id)
,其中所有其他私有函数都有一个http请求,该请求可以给出有效响应或错误
有没有办法通过模仿所有其他私有函数来测试公共函数。我想预先定义每个私有函数将返回的数据以及它们从env获取并用于发送请求的主要数据。您可以使用
nock
()模拟所有http调用,并测试您通常会执行的公共函数
class FetchTenant {
constructor (){
this.Config = this._getConfig();
this.Token = this._getToken();
this.TenantMap = new Map();
}
async getTenantId(Id){
if(!this.TenantMap[Id]){
const serviceid = await this._getInfo(Id, false);
this.TenantMap[Id] = serviceid;
}
return this.TenantMap[Id];
}
_getConfig() {
return get_env_from_local({ name: 'env_1' });
}
async _getToken() {
const options = {
method: 'POST',
uri: `${this.Config.url}`,
json: true,
resolveWithFullResponse: false,
transform2xxOnly: true,
transform: body => body.access_token,
auth: {
username: this.Config.clientid,
password: this.Config.clientsecret
},
form: {
grant_type: 'client_credentials'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
return request(options)
.catch(err => {
logger.error('Could not get Token', err.statusCode, err.message);
return null;
});
}
async _getInfo(Id, newtoken) {
if(newtoken){
this.accessToken = await this._getToken();
if(this.accessToken == null){
logger.error(`fetching token failed`);
return null;
}
}
const options = {
method: 'GET',
uri: `${this.Config.url}/xyz/${Id}`,
json: true,
resolveWithFullResponse: false,
transform2xxOnly: true,
transform: body => body.tenantId,
auth: {
bearer: this.accessToken
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
return request(options)
.catch(err => {
if(err.statusCode != 401) {
logger.error(`Could not get tenant id`, err.statusCode, err.message);
return null;
}
else {
return this._getServiceInstanceInfo(Id, true);
}
});
}
}
module.exports = FetchTenant;