Frozen Crayon
Frozen Crayon

Reputation: 5400

How to test a function that returns functions?

Here I have a function generateBlocks that takes in an array blocks and a function onBlockClick. It returns an array of object where each object has two properties label and onClick.

function generateBlocks(blocks, onBlockClick){
   return blocks.map(block => (
     {
        label: block.label,
        onClick: ()=>onBlockClick(block.name)
     }
 ))
}

I'm unable test it's return value. Here's the test case:

const blocks = [{label: "A", name: "a"}, {label: "B", name: "b"}];
const onBlockClick = someFunction(){};

expect(generateBlocks(blocks, onBlockClick)).to.deep.equal(expected)

I cannot create expected as [[{label: "A", onClick: ()=>onBlockClick("A")},...] because function reference will be different.

So how do I refactor generateBlocks function to make it testable?

Upvotes: 4

Views: 2403

Answers (1)

Martin Chaov
Martin Chaov

Reputation: 864

You can use .toString() method on the function ref and compare to expected string result.

Upvotes: 1

Related Questions