0

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?

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.