简体   繁体   中英

Run tests multiple times with different beforeEach

So I have these 2 cases in my tests. First one works fine, in the second one I try to extract the beforeEach declaration outside and it fails but I don't understand why. This is a simple case, basically I try to define an array and make a loop on that in order to run the tests multimple time with different beforeEach params declaration.

CASE 1

var params;

describe('When initializing', function () {
    beforeEach(function () {
        params = {
            name: 'test 1'
        };         
    });

    it('should ..', function () {                              
        params.name = 'test 2';
        expect(...); => success
    });

    it('should ..', function () {                              
        expect(...); => success because it expects params.name to be 'test 1' and it is 'test 1'
    });
});

CASE 2

var params;

var test = {
    name: 'test 1'
};

describe('When initializing', function () {
    beforeEach(function () {
        params = test;            
    });

    it('should ..', function () {                              
        params.name = 'test 2';
        expect(...); => success
    });

    it('should ..', function () {                              
        expect(...); => fails because it expects params.name to be 'test 1' and it is 'test 2'
    });
});

In the second test if I console.log(test.name) inside the describe I will get test 2 , somehow it got overriden even though the previous it did just params.name = 'test 2'; and not test.name = 'test 2';

The difference is that in case 1 you're creating a new object every time beforeEach is called, while in case 2 you're not.

Combined with that is the fact that your first test mutates the object. If all the tests are referring to the same object (ie, case 2) then that mutation will affect any code that runs after the first test. If instead the object is overwritten before each test (case 1), then the mutation won't affect other tests.

There are a few options for how to address this. One is to just to keep case 1; by resetting to a known state each time, you can have a clean state for all the tests to work off of. Another option is to not mutate the object. Perhaps the tests could copy the object and then modify that copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM