What's a good way to reuse test code using Jasmine?

前端 未结 8 624
無奈伤痛
無奈伤痛 2020-12-05 07:01

I\'m using the Jasmine BDD Javascript library and really enjoying it. I have test code that I\'d like to reuse (for example, testing multiple implementations of a base clas

8条回答
  •  感动是毒
    2020-12-05 07:49

    Let me summarize it with working example

      describe('test', function () {
    
        beforeEach(function () {
          this.shared = 1;
        });
    
        it('should test shared', function () {
          expect(this.shared).toBe(1);
        });
    
        testShared();
      });
    
      function testShared() {
        it('should test in function', function() {
          expect(this.shared).toBe(1);
      });
    
      }
    

    The crucial parts here are this keyword to pass context and because of this we have to use "normal" functions (another crucial part).

    For production code I would probably use normal function only in beforeEach to pass/extract context but keep to use arrow-function in specs for brevity.

    Passing context as parameter wouldn't work because normally we define context in beforeEach block wich invoked after.

    Having describe section seems not important, but still welcome for better structure

提交回复
热议问题