简体   繁体   中英

sinon stub an array object

Having read the official documentation and searched, but I still have no idea about this.

Simple Source Code:

// obj is an object with an array element
// each element in array has its function
if (obj.arr['key1']) {
    return obj.arr['key1'].getValue();
}

What I want is controlling obj.arr , for example:

var stub = sinon.stub(obj, "arr");
stub['key2'].returns = {...} //add new Index 
delete stub['key1'].returns //remove old Index

You can stub a function in an array like this:

myObj = {

    myArray: [
    function(){}, 
    function(){}, 
    function(){}
    ]
}

var stub = sinon.stub(myObj.myArray, [0]).returns() //insert what should be returned

Use:

describe ('foo', function () {

    it ('foo', sinon.test(function () {

        this.stub (myObj.myArray, [0]).returns();

    }))
}

if you want automatic cleanup after your stubs.

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