嘲笑同一对象的多个方法时,Sinan存根(sinn stub)返回空响应

时间:2018-08-16 11:43:47

标签: javascript node.js sinon sinon-chai

我正在尝试使用sinon在对象中模拟两个方法。其中一个返回预期的响应,但另一个方法返回一个空的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");
    });
  });
});

updatestate方法的源代码

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的源代码也与上面类似。

如何在同一个方法中模拟多个方法,以使其返回预期的响应。

1 个答案:

答案 0 :(得分:1)

您如何使用存根(stub)是正确的,应该可以使用。而且它们实际上正在工作,问题在于此处的模拟方法正在返回promise(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