Fix `replaceWith` method

Ensure that node structures are updated accordingly and update the tests
to verify the expected behavior of the method.