Search code examples
node.jssinonstub

How to compare an argument as an object use sinon?


I'm using sinon stub to mock the response from 3rd party. Everything is fine since I need to check the input of function called.

Example: I create a function to get user information, use Mongoose to get data from mongodb.

async function getUser(userId) {
  const userInfo = await User.findOne({ _id: userId });
  return userInfo;
}

My UT:

describe('Test user', () => {
  let findOneUserStub;
  beforeEach(() => {
    findOneUserStub = sinon.stub(User, 'findOne');
  });

  afterEach(() => {
    findOneUserStub.restore();
  });

  // Work
  it('Should return information success', async () => {
    const response = await getUser('userId_01');
    findOneUserStub.returns({ _id: 'userId_01'});
    expect(response).to.be.equals({ _id: 'userId_01'});
  });

  // Not work
  it('Should return information success', async () => {
    const response = await getUser('userId_01');
    findOneUserStub.withArgs({ _id: 'userId_01'}).returns({ _id: 'userId_01'});
    expect(response).to.be.equals({ _id: 'userId_01'});
  });
})

I think it only able compare with value variable, is cannot compare with reference variable. So do we have any way to compare reference variable?


Solution

  • I think you can use this:

    sinon.assert.calledWithExactly(findOneUserStub, {
     _id: 'userId_01'
    })
    

    https://sinonjs.org/releases/latest/assertions/