vendredi 9 août 2019

How do I mock a jquery result so that new XMLSerializer().serializeToString($(id)[0]) can run?

I have the line:

var svg = new XMLSerializer().serializeToString($(id)[0]);

as part of a function that I need to test.

I need to mock $(id)[0] so that the line doesn't cause errors. (Stubbing serializeToString would be acceptable as well but I'm completely unsure about how to stub the function)

I am using Sinon and running jsTestDriver from PHPStorm.

Versions I am using:

jQuery JavaScript Library v1.11.1

Sinon version 7.3.2, 2019-04-17

I tried

var the$ = sinon.stub(window, '$');
the$.withArgs('#testDownloadPNG').returns({
    0: "svg string" 
});

but that wasn't valid input for serializeToString.

https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer/serializeToString says that new XMLSerializer().serializeToString needs a node so I tried:

var the$ = sinon.stub(window, '$');
the$.withArgs('#testDownloadPNG').returns({
    0: new Node()
});

which is clearly incorrect as I got the error:

TypeError: Illegal constructor
at b.ActionsTestButton.setUp (http://127.0.0.1:9876/test/tests/Functional/javascriptTests/actionsTestButtonActionsFunctions.test.js:11:12)

(line 11 is the new Node() line)

I tried to stub serializeToString using:

var xmlStub = sinon.stub(XMLSerializer, 'serializeToString');

but I got the error:

 TypeError: Cannot stub non-existent own property serializeToString
at Sandbox.stub (http://127.0.0.1:9876/test/tests/Dependencies/sinon732.js:2116:27)
at b.ActionsTestButton.testDownloadAsPNG (http://127.0.0.1:9876/test/tests/Functional/javascriptTests/actionsTestButtonActionsFunctions.test.js:455:25)

I want the line to not cause errors and svg to be a string so the rest of the function can be tested.

Aucun commentaire:

Enregistrer un commentaire