首页 > 解决方案 > 使用 Sinon onCall 方法时出现意外结果

问题描述

我遇到了一个意外的结果:“应该获取数据并且有多个记录集”测试用例。我的意图是让“stub.getRefundItems”方法调用在第一次调用时返回一组结果,在第二次调用时返回第二组结果。如果没有使用该方法的其他测试,则该测试将按预期工作。但是,当我添加附加测试“应该获取数据并具有 1 个记录集”时,无论我做什么,我都会得到一个结果 (LineItemsHasNextFalse)。我还应该提到存根通过 awilix 作为单例注入。我是否错误地将存根接线?设置返回值后,是否无法使用 onCall 更改结果?

let stub = {
    getRefund: sandbox.stub(),
    getRefunds: sandbox.stub(),
    getRefundItems: sandbox.stub(),
    getRefundTransactions: sandbox.stub()
};

var sandbox = require('sinon').createSandbox();

describe('#refunds', function() {
   
    beforeEach(function () {
         sandbox.spy(logger)
     })
 
     afterEach(function () {
         // completely restore all fakes created through the sandbox
         sandbox.restore();
     })

     context('getRefundItems', function() {

        it('should get data and has 1 recordSet', test(async function() {
            stub.getRefundItems.returns(LineItemsHasNextFalse)
            
            let resp = await refunds.getRefundItems({"gid":"shjdjs"})

            expect(resp).to.deep.equal(LineItemsHasNextFalse.data.refund.refundLineItems.edges)
        }))

        it('should get data and has multiple recordSets', test(async function() {
            let correctResp = new Array()
            correctResp.push(...LineItemsHasNextTrue.data.refund.refundLineItems.edges)
            correctResp.push(...LineItemsHasNextFalse.data.refund.refundLineItems.edges)

            stub.getRefundItems.onCall(0).returns(LineItemsHasNextTrue)
            stub.getRefundItems.onCall(1).returns(LineItemsHasNextFalse)

            let resp = await refunds.getRefundItems({"gid":"shjdjs"})

            console.log(resp)
            expect(resp).to.deep.equal(correctResp)
        }))
    })
})

async getRefundItems(msgObj)
    {
        let hasNext = false
        let items = []
        let count = 0
        do
        {
            let response = await stub.getRefundItems(msgObj)
            if(response.data.refund != null)
            {
                items.push(...response.data.refund.refundLineItems.edges)
                if(response.data.refund.refundLineItems.pageInfo.hasNextPage)
                {
                    let cursor = response.data.refund.refundLineItems.edges[0].cursor
                    msgObj.after = cursor
                    hasNext = true
                }
                else
                {
                    hasNext=false
                }
            }
        }
        while(hasNext)
        return items
    }

标签: sinon

解决方案


推荐阅读