Tuesday, June 4, 2024
109
rated 0 times [  110] [ 1]  / answers: 1 / hits: 16055  / 7 Years ago, thu, september 14, 2017, 12:00:00

Using sinon and enzyme I wanna test the following component:



// Apple.js
class Apple extends Component {

componentDidMount = () => {

this.props.start();
Api.get()
.then(data => {
console.log(data); // THIS IS ALWAYS CALLED
this.props.end();
});
}

render () {
return (<div></div>);
}
}


If I just check endApy.called, it's always false. But wrapping it in a setTimeout will make it pass. Why console.log() is always called but not the props.end? Why setTimeout fixes it? Is there a better way of doing this?



// Apple.test.js
import sinon from 'sinon';
import { mount } from 'enzyme';
import Api from './Api';
import Apple from './Apple';


test('should call end if Api.get is successfull', t => {
t.plan(2);
sinon
.stub(Api, 'get')
.returns(Promise.resolve());

const startSpy = sinon.spy();
const endApy = sinon.spy();

mount(<Apple start={ startSpy } end={ endApy } />);

t.equal(startSpy.called, true); // ALWAYS PASSES
t.equal(endSpy.called, true); // ALWAYS FAILS
setTimeout(() => t.equal(endApy.called, true)); // ALWAYS PASSES

Api.get.restore();
});

More From » unit-testing

 Answers
54

Api.get is async function and it returns a promise, so to emulate async call in test you need to call resolves function not returns:




Causes the stub to return a Promise which resolves to the provided value. When constructing the Promise, sinon uses the Promise.resolve method. You are responsible for providing a polyfill in environments which do not provide Promise.




sinon
.stub(Api, 'get')
.resolves('ok');

[#56478] Tuesday, September 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
berenices

Total Points: 104
Total Questions: 106
Total Answers: 106

Location: Spain
Member since Thu, Dec 23, 2021
3 Years ago
berenices questions
;