Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing D3.js drag events with Cypress.js

I have an SVG object which uses d3-zoom for zoom and pan functionality. It works flawlessly but the problem showed up when I started to work on integration tests using Cypress.js.

I tried using standard mouse events on the svg element, to simulate drag behavior:

cy.get('svg')
  .trigger('mousedown', { which: 1, force: true })
  .trigger('mousemove', { position: 'left' })
  .trigger('mouseup', { position: 'left', force: true });

The example above is taken from the Cypress drag and drop recipe, and it produces the following error in the nodrag.js file:

cannot read property document of undefined

Below you can see where the error occurs (view is undefined):

__webpack_exports__["default"] = (function(view) {
  var root = view.document.documentElement,
  ...

I spent a lot of hours trying to trigger the event in another way, but without a success - like trying the snippet above with the svg container.

Please keep in mind that I cannot access any d3.js package from the Cypress test because it's imported as an NPM package in a React application.

Thank you in advance for you help!

like image 328
Damian Bartosik Avatar asked Jan 03 '19 18:01

Damian Bartosik


1 Answers

Try this:

cy.window().then(win => {
  cy.get('svg')
    .trigger('mousedown', {
      which: 1,
      force: true,
      view: win,
    })
    .trigger('mousemove', {
      clientX: 300,
      clientY: 500,
      force: true,
    })
    .trigger('mouseup', {
      force: true,
      view: win,
    });
});

Referencing Jennifer Shehane's answer in this GitHub issue, the answer to the cannot read property document of undefined part is to plug the window object into view in the trigger options. The issue mentioned in jacefarm's answer, where no movement occurred, seems to be resolved by specifying clientX/clientY rather than using positions relative to the selected element.

like image 74
Chris Avatar answered Sep 18 '22 12:09

Chris