使用Jasmine重用测试代码的好方法是什么?

gle*_*enn 21 javascript bdd jasmine

我正在使用Jasmine BDD Javascript库并且非常享受它.我有测试代码,我想重用(例如,测试基类的多个实现或在稍微不同的上下文中运行相同的测试),我不知道如何使用Jasmine.我知道我可以将代码从jasmine函数移到可重用的类中,但我喜欢代码读取散布Jasmine函数的方式(描述,它),我不想将规范与测试代码分开,除非我不得不.有没有人使用Jasmine遇到这个问题,你是如何处理它的?

小智 28

以下是Pivotal Labs的一篇文章,其中详细介绍了如何打包描述调用:

用共享行为干掉Jasmine规范

文章中显示部分包装函数的片段:

function sharedBehaviorForGameOf(context) {
  describe("(shared)", function() {
    var ball, game;
    beforeEach(function() {
      ball = context.ball;
      game = context.game;
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 当我尝试本文中的代码时,传入的范围(篮球或橄榄球)在beforeEach函数运行之前传入,因此是一个空对象.我通过传入一个构造函数的实例来解决这个问题.但我仍然对戴维斯的代码如何运作感到好奇.我错过了什么吗? (4认同)

Jur*_*uri 13

我不确定@ starmer的解决方案是如何运作的.正如我在评论中提到的,当我使用他的代码时,context总是未定义的.

相反,你必须做的事情(如@moefinley所提到的)是传递对构造函数的引用.我写了一篇博文,用一个例子概述了这种方法.这是它的本质:

describe('service interface', function(){
    function createInstance(){
        return /* code to create a new service or pass in an existing reference */
    }

    executeSharedTests(createInstance);
});

function executeSharedTests(createInstanceFn){
    describe('when adding a new menu entry', function(){
        var subjectUnderTest;

        beforeEach(function(){
            //create an instance by invoking the constructor function
            subjectUnderTest = createInstanceFn();
        });

        it('should allow to add new menu entries', function(){
            /* assertion code here, verifying subjectUnderTest works properly */
        });
    });
}
Run Code Online (Sandbox Code Playgroud)


gle*_*enn -11

有人向我指出将描述调用包装在向其传递参数的函数中。

  • 你至少应该粘贴一个片段 (8认同)