How to Write Rock Solid Tests for React in Webdriver.io
I like my end-to-end tests in Cucumber. But testing a React application has it’s specifics. The code is for an older version Webdriver 4, but with small changes it will work for version 5.
A component (a node in DOM) can be rerendered any time. Don’t assign references and use finders everywhere. Don’t worry, it’s fast.
Usually there aren’t any problems with rerenders as webdriver can recover and find it again. But well, not always - there are some API methods which will say elements is stale and throw “referenced element is no longer available”.
const form = $('.my-form'); form.$('#name').setValue('blah'); form.$('.my-form__submit').click();
$('.my-form #name').setValue('blah'); $('.my-form__submit').click();
or in helper:
browser.waitUntil( () => expect($('.header')).to.contain('Users'), undefined, 'Header "Users" could not be found', );
or implement loaders in your application and then:
// wait until it doesn't exist browser.waitForExist('.loader', undefined, true); expect($('.header')).to.contain('Users');
There are two main issues which will manifest like everywhere. Don’t be afraid to use
waitUntil(), just default message is shit and cryptic, so provide your own. Probably create a helper for this. And don’t save finders to a variable if you don’t have to.