Priya
Priya

Reputation: 69

Sinon stub returns empty response when mocking multiple methods of same object

I am trying to mock two methods in a object using sinon. One of it returns the expected response but the other method returns an empty 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");
    });
  });
});

Source code for updatestate method

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 });
                }
            }
        });
    });
}

}

The source code for getState is also similar to the above.

How to mock multiple methods in the same method so that it returns the expected response.

Upvotes: 0

Views: 1836

Answers (1)

dereli
dereli

Reputation: 1864

How you use the stubs are correct and should work. And they are actually working, the problem is the mock methods here are returning promises (Promise.resolve(JSON.parse(...))).

      console.log(
        "before testing" +
          JSON.stringify(DataApi.prototype.updatePromoteState())
      ); // returns {} instead of response json

The code above tries to log the promise, not the actual value.

You can add an await keyword before the function call and change the fn function to async. So it becomes more or less:

  const fn = async () => {
    try {
      console.log(
        'before testing' + JSON.stringify(DataApi.prototype.updateState()),
      );
    } catch (error) {
      throw error;
    }
  };

or remove Promise.resolves within stub functions.

Upvotes: 1

Related Questions