2

I need to Mock getZvalue so , when i do a shallow based on z value i will try to render something different . How do i test it . Below is sample code . can i spy this method to return a value

class AbcComponent extends React.Component{
  render(){
    const z= this.getZValue();
    return <div>{z}</div>

  }

  getZValue(){
    //some calculations 
    }
  }


describe('AbcComponent',()=>{
  it('Test AbcComponent',()=>{
    const wrapper= shallow<AbcComponent/>
  })
})
anoop
  • 3,229
  • 23
  • 35
Kamaraju
  • 2,365
  • 2
  • 15
  • 17

1 Answers1

2

How about this?

import { spy } from 'sinon';
describe('AbcComponent',()=> {
  it('Test AbcComponent',()=> {
    spy(AbcComponent.prototype, "getZValue");
    const wrapper= shallow<AbcComponent/>
    expect(AbcComponent.prototype.getZValue.callCount).to.equal(1);
    AbcComponent.prototype.getZValue.restore();
  })
})

Adding to this, you can test with return values as follows,

   import { stub } from 'sinon';
    describe('AbcComponent',()=> {
      it('Test AbcComponent',()=> {
        stub(AbcComponent.prototype, "getZValue").returns(10);
        const wrapper= shallow<AbcComponent/>
        expect(AbcComponent.prototype.getZValue.callCount).to.equal(1);
        AbcComponent.prototype.getZValue.restore();
      })
    })
anoop
  • 3,229
  • 23
  • 35