How to use sinon to stub/mock "this.userId" inside method

Is it possible to use sinon to set this.userId value which called inside method and publication?
I can stub Meteor.user and Meteor.userId but this.userId doesn’t work.

interface CallAsyncStubbed {
  user: (object & { _id: string }) | null;
  method: string;
  args: any[];
}
/**
 * Stub Meteor.user() during the calling of a Meteor method
 */
export const callAsyncStubbed = async <T>({
  user,
  method,
  args,
}: CallAsyncStubbed) => {
  if (!user && user !== null)
    throw new Error("stubUserCall requires object or null");

  const userStub = sinon.stub(Meteor, "user");
  userStub.returns(user);
  const userIdStub = sinon.stub(Meteor, "userId");
  userIdStub.returns(user ? user._id : null);

  try {
    const result: T = await Meteor.callAsync(method, ...args);
    userStub.restore();
    userIdStub.restore();
    return result;
  } catch (err) {
    userStub.restore();
    userIdStub.restore();
    throw err;
  }
};
1 Like