TDD – How to TDD for a Bug That Can Only Be Tested After Fixing

language-agnostictddunit testingvisual-testing

Here's one example: My web application contains draggable elements. When dragging an element, the browser produces a "ghost image". I want to remove the "ghost image" when dragging and I write a test for this behaviour.

My problem is that I initially have no idea how to fix this bug and the only way I can write a test is after I have fixed it.

In a simple function such as let sum = (a, b) => a - b, you can write a test as to why sum(1, 2) does not equal 3 before writing any code.

In the case I am describing, I can't test, because I don't know what the verification is (I don't know what the assertion should be).

A solution to the problem described is:

let dataTransfer = e.dataTransfer
let canvas = document.createElement('canvas');
canvas.style.opacity = '0';
canvas.style.position = 'absolute';
canvas.style.top = '-1000px';
dataTransfer.effectAllowed = 'none';

document.body.appendChild(canvas);
dataTransfer.setDragImage(canvas, 0, 0);

I could not have known that this was the solution. I could not even have written the test after finding the solution online, because the only way I could have known if it really worked, was to add this code into my codebase and verify with the browser if it had the desired effect. The test had to be written after the code, which goes against TDD.

What would be the TDD approach to this problem? Is writing the test before the code mandatory or optional?

Best Answer

When I understood you correctly, you cannot even write a reliable automated test for your "ghost image" example after you found a solution, since the only way of verifying the correct behaviour is to look at the screen and check if there is no ghost image any more. That gives me the impression your original headline asked the wrong question. The real question should be

  • how to automatically test a certain behaviour of a graphical user interface?

And the answer is - for several kind of UI issues, you don't. Sure, one can try to automate making the UI showing the problem somehow, and try to implement something like a screenshot comparison, but this is often error-prone, brittle and not cost-effective.

Especially "test driving" UI design or UI improvements by automated tests written in advance is literally impossible. You "drive" UI design by making an improvement, show the result to a human (yourself, some testers or a user) and ask for feedback.

So accept the fact TDD is not a silver bullet, and for some kind of issues still manual testing makes more sense than automated tests. If you have a systematic testing process, maybe with some dedicated testers, best thing you can do is to add the case to their test plan.

Related Topic