0

I have next function:

fillText: function(text) {  
    this.node.innerHTML = text;

    return {
        width: this.node.clientWidth,
        height: this.node.clientHeight
    };
},

And unit test for it:

it('Should return width and height of text node.', function() {
    var sizeInPx = unit.fillText('ABCDEFGHIJKLMNOPQRSTUVWXYZ');

    // width and height of text is different for different browsers
    var widths = [408, 413, 421];
    var heights = [13, 14];

    expect(sizeInPx.width).to.be.oneOf(widths);
    expect(sizeInPx.height).to.be.oneOf(heights);
});

This test is non cross-platform, because widths and heights specified for different browsers (Chrome, IE ...). And at now this test fails on MacOS.

How to test that function right?

1 Answer 1

1

You say you want to unit-test your function, but what you actually do is integration testing: With unit-testing you focus on finding those bugs in a small piece of code that can be found by testing the code in isolation. You, instead, test the code in combination with several browsers to see if it works together with each of these browsers, which is integration testing. Which is oK - there is nothing wrong in principle with doing integration testing.

What is problematic, however, is that your tests are extremely fragile: The tests are overspecified. It is not really of importance that the exact values are returned, and the situation that the values change does not indicate a bug, neither in your isolated code, nor in the interaction with the browser, nor in the browser itself: The values are likely to be different between different browsers (as you are aware of), but possibly also between different versions of the same browser, between different versions of some font files, and possibly even between different startups of the same browser or even between different executions of the code within the same session of the same browser, for example if other parameters have been changed during the session like default font.

So, how could you then improve your tests? Step away from concrete numbers and, for example, check that a) both elements width and height are positive integral numbers, b) check that the width is larger than the height, which should be the case for a text like 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', c) test that for 'A<br>B<br>C...' the height is larger than the width.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.