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

前端 未结 8 623
無奈伤痛
無奈伤痛 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:58

    This is the approach I have taken, inspired by this article:

    https://gist.github.com/traviskaufman/11131303

    which is based on Jasmine own documentation:

    http://jasmine.github.io/2.0/introduction.html#section-The_%3Ccode%3Ethis%3C/code%3E_keyword

    By setting shared dependencies as properties of beforeEach function prototype, you can extend beforeEach to make this dependencies available via this.

    Example:

    describe('A suite', function() {
        // Shared setup for nested suites
        beforeEach(function() {
            // For the sake of simplicity this is just a string
            // but it could be anything
            this.sharedDependency = 'Some dependency';
        });
    
        describe('A nested suite', function() {
            var dependency;
    
            beforeEach(function() {
                // This works!
                dependency = this.sharedDependency;                
            });
    
            it('Dependency should be defined', function() {
                expect(dependency).toBeDefined();
            });
        });
    
        describe('Check if string split method works', function() {
            var splitToArray;
    
            beforeEach(function() {
                splitToArray = this.sharedDependency.split();                
            });
    
            it('Some other test', function() { ... });
        });
    });
    

    I know my example is kind of useless but it should serve its purpose as code example.

    Of course this is just one of the many things you could do to achieve what you say, I'm sure that more complex design patterns may be applied on top or aside to this one.

    Hope it helps!

提交回复
热议问题