0

I am using Puppeteer to do some testing on a React app. The problem is that controlled inputs do not save their values into the Virtual DOM or state of the application when interacting with them by simply setting the DOM value.

After several days of research I came up with the following solution based on this reply:

describe('<HomePage />', async () => {
  eval('jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;'); //eslint-disable-line
  it('should make some new element visible', async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto('http://localhost:3000/links');
    await page.waitForSelector('input', { visible: true });
    await page.addScriptTag({ url: 'https://code.jquery.com/jquery-3.2.1.min.js' });
    const someNewElement = await page.evaluate(() => {
      const $ = window.$;

      function doEvent(obj, event) {
      /* Created by David@Refoua.me */
        const newEvent = new Event(event, { target: obj, bubbles: true });
        return obj ? obj.dispatchEvent(newEvent) : false;
      }

      const mySelect = $('[name="mySelect"]')[0];
      mySelect.value = 'MakeSomeNewElementVisible';

      // for input dispatch -> input, for select dispatch -> change
      doEvent(mySelect, 'change');

      return $('#someNewElement_was_made_visible').length;
    });
    expect(someNewElement).toEqual(1);
    setTimeout(() => { browser.close(); }, 3000);
  });
});

My question is: How do I replace the doEvent function with some jQuery function?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Tudor Morar
  • 3,720
  • 2
  • 27
  • 25

1 Answers1

1

Here is a far better solution for your problem, I assume you are trying to select an option from a list, in that case, simply use the following,

page.select('[name="mySelect"]', 'MakeSomeNewElementVisible');

You can tweak the selector if this was not the appropriate one. I'd suggest letting puppeteer do the heavy lifting for you.

If you still need to dispatch some event using .evaluate, you can look into this answer, or this one.

Make sure to wait for a while after you do some event, some event might have some transition/delay added to them. Otherwise you might end up returning the result even before the element is visible in the dom.

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73