编程语言
首页 > 编程语言> > javascript – QUnit:每个方法一个测试,每个方法有多个断言或多个测试?

javascript – QUnit:每个方法一个测试,每个方法有多个断言或多个测试?

作者:互联网

我决定为我的下一个javascript项目开始TDD,我正在使用QUnit进行单元测试.我完全不熟悉单元测试,从未使用过任何语言.下面是我的一个模块的示例以及一个尝试覆盖此方法将遇到的所有方案的find方法的测试:

module("TextSwapper", {
    setup: function() { 
        this.str = 'When you first start off trying to solve a problem, the first solutions you come up with are very complex, and most people stop there. But if you keep going, and live with the problem and peel more layers of the onion off, you can often times arrive at some very elegant and simple solutions.';

        this.ts = new TextSwapper();
        ok(this.ts, 'The TextSwapper was created successfully');

        this.textarea = document.createElement('textarea');
        this.textarea.value = this.str;
        document.body.appendChild(this.textarea);
    },
    teardown: function() {
            document.body.removeChild(this.textarea);
    }
});

test("find()", function() {
    equal(this.ts.find('When'), false, "Check it fails gracefully when no input has been set.");
    this.textarea.focus();
    equal(this.ts.find('When'), true, "Check it finds 'When' if the textarea has focus but no input has been set.");

    this.ts.setInput(this.textarea);
    this.ts.find('When');
    equal(window.getSelection().toString(), 'When', 'The word \'When\' should be highlighted');
    equal(this.ts.found[0][0], 'When', 'The word \'When\' should be in the found array');

    this.ts.find('you');
    equal(window.getSelection().toString(), 'you', 'The word \'you\' should be highlighted');
    equal(this.ts.found[1][0], 'you', 'The word \'you\' should be in the found array');
    equal(this.ts.found.length, 4 ,'Should have found 4 you\'s');

    this.ts.find('bill');
    equal(this.ts.found.length, 0, 'Check that nothing was found for \'bill\'');

    this.ts.find('[a-z]*ee[a-z]*');
    equal(window.getSelection().toString(), 'keep', 'The word \'keep\' should be highlighted');
    equal(this.ts.found[1][0], 'peel', 'The word \'peel\' should be in the found array');
    equal(this.ts.found.length, 2 ,'Should have found 2 for [a-z]*ee[a-z]*');

});

我的问题是我是以正确的方式来做这件事的吗?我的测试中有太多断言吗?我的测试应该分解成更小的测试吗?我一直在阅读关于stackoverflow的TDD,我现在已经阅读了一些让我觉得我做错了的事情.

解决方法:

如果您正在使用TDD,那么您应该针对每种测试方法进行一次断言.

以下链接可以很好地解释在一种方法中测试所有内容时可能遇到的问题:Unit testing它可以更容易地在代码中引入隐藏的错误.

标签:qunit,javascript,unit-testing
来源: https://codeday.me/bug/20190902/1793833.html