简体   繁体   中英

How to stub a class with Sinon.js

I am trying to write a simple test for a function who call the OVH api.

I don't understand, my sinon.js stub dont "divert" the requestPromised method of ovh api . The sinon.js's stub work differently with a class object ?

My function (myOvhApi.js) :

const ovh = require('ovh')({
  endpoint: 'Endpoint',
  appKey: 'AppKey',
  appSecret: 'appSecret',
  consumerKey: 'ConsumerKey'
})

exports.myFunction = async ( ipAdress, subDomain, ovhDynDNSId ) => {

  try{
    await ovh.requestPromised( 'PUT', `/domain/zone/${zone}/dynHost/record/${ovhDynDNSId}`,
      {
        'ip': ipAdress,
        'subDomain': subDomain
      })
  } catch (error) {
    console.log(error)
  }

  return true
}

My test:

const ovh = require('ovh')
const myOvhApi = require('myOvhApi')

describe('description', () => {

  it('description', async () => {

    const zone = 'mydomain.com'
    const ovhDynDNSId = '12345'
    const ipAdress = '127.0.0.1'
    const subDomain = 'subDomain'

    sinon.stub( ovh, 'requestPromised' ).returns(true)

    const expectation = await myOvhApi.myFunction ( ovhDynDNSId, ipAdress, subDomain )
    expect( expectation ).to.equal(true)
  })
})

Thank you

In my experience stubbing a function without describing all of the parameters for the function - the stub does not catch it.

Write your stub this way:

 sinon.stub( ovh, 'requestPromised', (method, uri) => { return true } 

Or you can also use the callsfake method from sinon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM