заглушка никогда не вызывается с помощью sinon и nodejs, используя chai-as-обещанный - PullRequest
0 голосов
/ 22 ноября 2018

У меня проблема с моим модульным тестом, он застрял полностью, код прост, пожалуйста, нужно понимать, что происходит, моя заглушка никогда не вызывается, набор, кажется, правильный, вот код:

let strategy = fixtures.load('strategy')
chai.use(chaiAsPromised)

describe.only('Spawn Order Job', () => {

  let getPositionsStub, createJobStub, daoStub,sandbox
  beforeEach(()=>{
    sandbox = sinon.createSandbox()
    daoStub = sandbox.stub(dao, 'updateActiveOrders').resolves(true) //async
    getPositionsStub = sandbox.stub(strategyModule, 'getPositions') //sync
    createJobStub = sandbox.stub(helpers, 'createJob') //sync
    createJobStub.returns(true)
    getPositionsStub.resolves([{fake:'t'}, {fake:'t'}])
  })

  afterEach(()=>{
    sandbox.restore()
  })
  //OK
  it('Should failed with no param, type error context', ()=> {
    const promise = spawnOrderJob()
    expect(promise).to.be.rejectedWith(TypeError)
  })


  //OK
  it('Should throw error timeout order', () => {
    getPositionsStub.resolves([{fake:'t'}, {fake:'t'}])
    strategy.lastDateOrder = new Date()
    const ctx = { state: {strategy, dashboard, position:null}}
    const action = {b: true, s: false}
    const promise = spawnOrderJob(action, ctx)
    expect(getPositionsStub.called).to.be.true
    expect(daoStub.called).to.be.false
    expect(createJobStub.called).to.be.false
    expect(promise).to.be.rejectedWith(ORDER_ERROR, 'Timeout between order not expired.')
  })

  //KO stub never called
  it.only('Should pass validation on buy', () => {
    strategy.lastDateOrder = 0
    const ctx = { state: {strategy, dashboard, position: null }}
    const action = {b: true, s: false}
    const promise = spawnOrderJob(action, ctx)
    expect(promise).to.be.fulfilled
    expect(getPositionsStub.called).to.be.true //ok
    expect(createJobStub.called).to.be.true //never callled ????
    expect(daoStub.called).to.be.true //never called ????
  })
})

Хотите понять, что там сейчас происходит, вызов правильный imo, работает с mocha 5.2

Helpers.js: функция описана следующим образом:

async function spawnOrderJob(action, ctx) {
  try {
    const { strategy, dashboard, position } = ctx.state
    const {b, s} = action

    //check in case strategy context
    if (strategy) {
      //pass validation buy contnext
      if (b) {
        //this stub is working
        const positions = await strategyModule.getPositions(ctx)

        const { maxPosition } = strategy.allocatedBTC
        const { activeOrders, maxActiveOrders, timeBetweenOrder, lastDateOrder } = strategy

        debug('Active orders:', strategy.activeOrders)
        debug('Position:', positions.length)

        if (activeOrders >= maxActiveOrders)
          throw new ORDER_ERROR('Max active orders reach.')

        if (positions.length + activeOrders >= maxPosition)
          throw new ORDER_ERROR('Max positions reach.')

        if (!timeoutExpired(lastDateOrder, timeBetweenOrder))
          throw new ORDER_ERROR('Timeout between order not expired.')

        //increment active orders counter
        //stub fail, but not called at all
        await dao.updateActiveOrders(strategy, true)
      }

      //Sell context
      if (s) {
        if (!position)
          throw new ORDER_ERROR('No position to sell')
      }
    }
    //stub fail, but called internally
    return createJob(constants.DASHBOARD_CREATE_ORDER, {
      orderType: b ? 'BUY' : 'SELL',
      title: `Strategy create order ( ${ b ? 'BUY' : 'SELL'} )`,
      strategy,
      dashboard,
      position
    })
  } catch (e) {
    throw e
  }
}


function createJob(name, data){
  //shortcut queue.create (kue.js)
  return queue.c(name,data)
}

module.exports = {
  createJob,
  spawnOrderJob
}

DAO

const updateActiveOrders = async (strategy, increment) => {
      try {
       const s = await model.findOne({_id: strategy._id})
        if (!s) throw new Error('Strategy not found.')
        s.activeOrders = increment ? s.activeOrders+1 :s.activeOrders-1
        s.lastDateOrder = new Date()
        return await s.save()
      }catch(e){
        throw e
      }
    }

module.exports = {updateActiveOrders}
...