【问题标题】:how to abstract and re-use a describe() block in jasmine?如何在茉莉花中抽象和重用 describe() 块?
【发布时间】:2016-01-05 11:06:41
【问题描述】:

我正在开发一个处理特定类型文档的 CRUD 的应用程序。因此,我们经常希望根据一组值测试该文档的一致性。我有一个内部带有 it() 的 describe() 块,用于测试该文档的每个字段。

我想让它可重用,但简单地围绕该描述块包装一个函数会导致时间问题,并且在该包装函数中的测试之前,以下测试运行得太早。

有没有一种模式可以做到这一点?应该是承诺吗? 我应该把它变成一个匹配器吗? docToBeEqualTo() ?我还没有看到在匹配器中使用 it(),它似乎不是适合这个的地方

我想我在这里缺少一个常见的模式。你能帮忙吗?

非常感谢

编辑:请求的代码示例:

function compareDocs(targetData, timeout){
        describe('the doc should contain : ', function(){
            it('The amount field should be : "' + targetData.amount + '". ', function(){
                expect(element(by.css(selector)).getAttribute('value')).toEqual(targetData.amount);
            }, timeout);


            it('The foo bar number  should be : "' + targetData.fooBar + '". ', function(){
                expect(element(by.css(selector)).getAttribute('value')).toEqual(targetData.fooBarNumber);

            }, timeout);

            return browser.waitForAngular();
        });
});

这样使用:

describe('first describe', function(){
            it('compare docs', function(){
               compareDocs(currentData,targetData);
            }, timeout);
});
describe('second describe where the doc is deleted', function(){
        it('should remove payment from list', function(){
              deleteDoc();//this runs too early, and delete the doc before compareDocs() has finished
              expect(element(by.css(selector)).isPresent).toBe(false);              
            }, timeout);
        });

TL;DR : 如何防止deleteDoc()compareDoc() 完成之前运行?

【问题讨论】:

  • 分享代码sn-p!
  • 不支持将itdescribe 嵌套在另一个it 块中。 its 应该有测试代码和期望; describe - 另一个 describe 和/或 it 的容器。

标签: javascript angularjs unit-testing jasmine protractor


【解决方案1】:

Jasmine 总是检查 describe 块和嵌套的 describe 函数。但是,当您在仅在被调用时执行的函数内定义套件(describe)或规范(it)时,量角器无法识别指定函数中的套件或规范。您可以使用循环或自执行函数来执行套件和规范(我想这不会解决您的问题)。唯一可能的解决方案是调用具有代码块的函数,其中没有任何套件或规范。这是一个例子-

function compareDocs(targetData, timeout){
    console.log('The amount field should be : "' + targetData.amount + '". ');
    expect(element(by.css(selector)).getAttribute('value')).toEqual(targetData.amount);
    console.log('The foo bar number  should be : "' + targetData.fooBar + '". ');       
    expect(element(by.css(selector)).getAttribute('value')).toEqual(targetData.fooBarNumber);
    return browser.waitForAngular();
};

注意:嵌套在 it 规范中的 describe 套件不会执行。

希望对你有帮助。

【讨论】:

  • 好吧,如果我是唯一的选择,我会这样做,谢谢你的帮助。我的问题对您来说似乎不常见/奇怪吗?我以为我在这里有一个相当普遍的需求。
  • 在测试中重复测试步骤似乎很常见。如前所述,当您编写循环或自执行函数代替您使用的函数时,您始终可以重复步骤。 Protractor 将所有describes 和its 都考虑在内,它可以在没有附加任何字符串的情况下执行(在您的情况下,这是一个仅在被调用时执行的函数),并将 jasmine2 的原则应用于它们。所以,是的,如果它被递归使用,你可以提出一个功能请求。
猜你喜欢
  • 1970-01-01
  • 2020-12-19
  • 2019-06-22
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 2015-02-10
  • 1970-01-01
相关资源
最近更新 更多