StackMaster
StackMaster

Reputation: 389

How to address nested functions using Sinon?

Using Sequelize in the code, I can't stub crucial inner functions of it, such as .save(), .scope(), etc.. Nesting doesn't seem to work.

As part of unit testing, the tests fail without proper handling of those functions, saying: TypeError: Cannot read property 'returns' of undefined

The error is being thrown during the execution of this line:

  subscription.save()

Implementation of the stub:

const deleteSubscription = async (subscriptionId) => {
  const ts = Math.floor(Date.now() / 1000)
  const subscription = await sql.Subscriptions.findByPk(subscriptionId);
  if (subscription == null) {
    throw new Error('Subscription not found', 'subscription_not_found')
  }
  subscription.deletedAt = ts
  subscription.save()
  return subscription
}

The unit-test:


    it('deleteSubscription succeeds', async () => {
        subscriptionsSqlStub.save.returns({})
        subscriptionsSqlStub.findByPk.returns({
            id: 1
        })
        const subscription = await subscriptions.deleteSubscription(subscriptionsSqlStub)
        expect(subscription).to.have.deep.property('id', 1)
        sinon.assert.calledOnce(subscriptionsSqlStub.findByPk)
        subscriptionsSqlStub.findByPk.resetHistory()
    })

How can I address the inner/nested functions?

Upvotes: 0

Views: 432

Answers (1)

deerawan
deerawan

Reputation: 8443

I haven't tried your code completely but I think it can be solved by adding save() in return response of findByPk so subscription.save() exists.

subscriptionsSqlStub.findByPk.returns({
  id: 1,
  save: () => true // adding save() here
});

Hope it works!

Upvotes: 1

Related Questions