How to test the args passed into document.body.appendChild with jest
As @Alex points out, document.createElement
creates an HTMLScriptElement
object.
You can test that the HTMLScriptElement
was created properly by checking its properties using expect.objectContaining
:
const doFunction = () => {
const s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://myscript';
s.id = 'abc';
document.body.appendChild(s);
}
test('doFunction', () => {
jest.spyOn(document.body, 'appendChild');
doFunction();
expect(document.body.appendChild).toBeCalledWith(
expect.objectContaining({
type: 'text/javascript',
src: 'https://myscript/',
id: 'abc'
})
); // Success!
});
You can assert that appendChild
is called with an HTML element, which is what document.createElement
returns.
expect(document.body.appendChild).toBeCalledWith(expect.any(HTMLElement));
You can further clarify your test by checking that it was called with a script element.
expect(document.body.appendChild).toBeCalledWith(expect.any(HTMLScriptElement));