模拟同一对象的多个方法时,Sinon stub returns 为空响应
Sinon stub returns empty response when mocking multiple methods of same object
我正在尝试使用 sinon 在一个对象中模拟两个方法。其中一种方法 returns 是预期的响应,但另一种方法 returns 是空的 json。
describe("Unit test cases ", () => {
describe("scenario 1", function() {
let getResponse, updateResponse;
before(function() {
getResponse = sinon
.stub(DataApi.prototype, "getState")
.returns(
Promise.resolve(
JSON.parse(
fs.readFileSync("./test/get-response.json").toString("utf8")
)
)
);
updateResponse = sinon
.stub(DataApi.prototype, "updateState")
.returns(
Promise.resolve(
JSON.parse(
fs.readFileSync("./test/update-response.json").toString("utf8")
)
)
);
});
after(function() {
getResponse.restore();
updateResponse.restore();
});
it("TC1", () => {
let event;
var fn = function() {
try {
console.log(
"before testing" +
JSON.stringify(DataApi.prototype.updatePromoteState())
); // returns {} instead of response json
handle(event, context, callback);
} catch (error) {
throw error;
}
};
expect(fn).to.not.throw("Successfully Processed");
});
});
});
更新状态方法的源代码
public updateState (authorization: string, xB3TraceId: string, xAppName?: string) : Promise<any> {
const localVarPath = this.basePath + '{abc}';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders);
let localVarFormParams: any = {};
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'PUT',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
json: true,
body: ObjectSerializer.serialize(promoteState, "PromoteState")
};
return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
}
getState的源码也和上面类似
如何在同一个方法中模拟多个方法,使其 returns 得到预期的响应。
您使用存根的方式是正确的,应该可以使用。他们实际上在工作,问题是这里的模拟方法正在返回承诺(Promise.resolve(JSON.parse(...))
)。
console.log(
"before testing" +
JSON.stringify(DataApi.prototype.updatePromoteState())
); // returns {} instead of response json
上面的代码尝试记录承诺,而不是实际值。
您可以在函数调用之前添加一个await
关键字,并将fn函数更改为异步。于是或多或少变成了:
const fn = async () => {
try {
console.log(
'before testing' + JSON.stringify(DataApi.prototype.updateState()),
);
} catch (error) {
throw error;
}
};
或删除存根函数中的 Promise.resolve
s。
我正在尝试使用 sinon 在一个对象中模拟两个方法。其中一种方法 returns 是预期的响应,但另一种方法 returns 是空的 json。
describe("Unit test cases ", () => {
describe("scenario 1", function() {
let getResponse, updateResponse;
before(function() {
getResponse = sinon
.stub(DataApi.prototype, "getState")
.returns(
Promise.resolve(
JSON.parse(
fs.readFileSync("./test/get-response.json").toString("utf8")
)
)
);
updateResponse = sinon
.stub(DataApi.prototype, "updateState")
.returns(
Promise.resolve(
JSON.parse(
fs.readFileSync("./test/update-response.json").toString("utf8")
)
)
);
});
after(function() {
getResponse.restore();
updateResponse.restore();
});
it("TC1", () => {
let event;
var fn = function() {
try {
console.log(
"before testing" +
JSON.stringify(DataApi.prototype.updatePromoteState())
); // returns {} instead of response json
handle(event, context, callback);
} catch (error) {
throw error;
}
};
expect(fn).to.not.throw("Successfully Processed");
});
});
});
更新状态方法的源代码
public updateState (authorization: string, xB3TraceId: string, xAppName?: string) : Promise<any> {
const localVarPath = this.basePath + '{abc}';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders);
let localVarFormParams: any = {};
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'PUT',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
json: true,
body: ObjectSerializer.serialize(promoteState, "PromoteState")
};
return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
}
getState的源码也和上面类似
如何在同一个方法中模拟多个方法,使其 returns 得到预期的响应。
您使用存根的方式是正确的,应该可以使用。他们实际上在工作,问题是这里的模拟方法正在返回承诺(Promise.resolve(JSON.parse(...))
)。
console.log(
"before testing" +
JSON.stringify(DataApi.prototype.updatePromoteState())
); // returns {} instead of response json
上面的代码尝试记录承诺,而不是实际值。
您可以在函数调用之前添加一个await
关键字,并将fn函数更改为异步。于是或多或少变成了:
const fn = async () => {
try {
console.log(
'before testing' + JSON.stringify(DataApi.prototype.updateState()),
);
} catch (error) {
throw error;
}
};
或删除存根函数中的 Promise.resolve
s。