javascript - Jasmine Unit Test: should I test the logic or the actual mocked data? -


when performing unit testing better test literal result expect hard-coding test (expect(x).tobe(17)), or better test logic , not specific mock data using (expect(x).tobe(mockeddata.value))

the first approach seems safer because sure test testing literal result expect, second approach more flexible since allows me test logic rather worry mock data (which can change later without having rewrite test itself)

what advantages/disadvantages of either approach? best practice in these cases?

following quick example:

// mockeddata long array of complex objects  // each of them has property 'value' of type number  import mockeddata 'data.mock';  class classtotest {     private data;     constructor(data) {         this.data = data;     }     plusone(): number {         return this.data.value + 1;     }  }  describe('test', () => {     let instance: classtotest;     beforeeach(() => {         instance = new classtotest(mockeddata[0]);     })     it('plusone() should return property "value" plus one', () => {         // should write this...         expect(instance.plusone()).tobe(mockeddata[0] + 1);         // ...or this?         expect(instance.plusone()).tobe(17); // because know mockeddata[0].value 16     })  }); 

thank much!! :)

in test want test unit, in case logic inside of plusone() function. want know if changes inside function.

the dangerous path use expect(instance.plusone()).tobe(17);, because if changes logic return this.data.value + 2;, never spot test if problem in function logic or in mockeddata.

the less dangerous approach use expect(instance.plusone()).tobe(mockeddata[0] + 1);, because tell if logic in function change. still not optimal, since depend on external mock run test don't need. why want depend on external mocked data test unit?

the best way test unit logic here this:

describe('test', () => {     let instance: classtotest;     const mockedvalue = 1;     beforeeach(() => {         instance = new classtotest(mockedvalue);     })     it('plusone() should return property "value" plus one', () => {         expect(instance.plusone()).tobe(mockedvalue + 1);     })  }); 

then, can implement separate tests service, here test logic inside plusone().


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -