views:

129

answers:

2

Hi all:

Suppose I have the following html:

var testString = '
<span id='id'>
    <div>
        <table>
            <span id='anotherId' class='NODE customContext' name='2'></span>
        </table>
    </div>
</span>'

and I want to convert it to a DOM structure using jQuery (under the assumption that jQuery is the best option to handle this task) as my unit testing data to test the following code:

$('#' + ID + ' > div > table').each(function() {
    var span = $(this).find('span.' + NODE)[0];
    .
    .
    .
});

Is this the way to convert the testString to DOM structure?

var jQueryDOMElement = $(testString);

Or am I way off the mark, or is there a better way to do it?

I just want to create a DOM structure without having to use createElement, elementNode... etc. I do not have access to test live, so I have to resort to using dummy test data/DOM structure.

Thanks!

+2  A: 

As far as I know, you must have a DOM element at first before you can create a complex structure (with a string). You might create a hidden DIV for testing and then jq('#unit-test').replaceWith(testString).

Mo
@Mo: I tried replacing a testSpan I added to the document (since I want to replace a span with another span). However after the replaceWith call, I can still find the removed span. Does that mean the replaceWith call didn't work? i.e. var testSpan = document.createElement("span"); testSpan.id = "testSpan"; testSpan.type = "hidden"; document.body.appendChild(testSpan); $("testSpan").replaceWith(jQueryDOMElement);
BeraCim
+2  A: 

have you tried using JSTestDriver for testing your javascript. It allows you to inject DOM elements as you need it straight from the test without having to worry about how to do it where to do it. The details are here.

I have started doing all my JS tests using this because it supports QUnit and YUI test for writting of tests. It also got good support for CI servers

AutomatedTester
@AutomatedTester: I am using JSTestDriver. This is exactly what I'm looking for. Thank you very much!
BeraCim