Created
February 5, 2018 08:06
-
-
Save promentol/c5c40d32980619d56be15e42f04958c2 to your computer and use it in GitHub Desktop.
Code Refactoring for making more testable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Meal = mongoose.model() | |
class MealService{ | |
changeCalories(id, calories){ | |
Meal.update(id, { | |
$set: {calories} | |
}) | |
} | |
} | |
//Test Code | |
it("should update calories", ()=>{ | |
const mealService = new MealService() | |
mealService.changeCalories(1, 1000) | |
/* It will mutate external state, on which we don't have controll everytime*/ | |
}) | |
//With dependency injection | |
class MealService{ | |
constructor(mealModel){ | |
this.mealModel = mealModel | |
} | |
changeCalories(id, calories){ | |
Meal.update(id, { | |
$set: {calories} | |
}) | |
} | |
} | |
//Test Code | |
it("should update calories", ()=>{ | |
const MealMockModel = { | |
update: ()=>(id, calories) { | |
/* | |
OUR ASSERTIONS | |
*/ | |
} | |
} | |
const mealService = new MealService(MealMockModel) | |
mealService.changeCalories(1, 1000) | |
/* It will mutate external state, on which we don't have controll everytime*/ | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Do not use explicit state | |
SomeService.getCaloriesPerGram() { | |
return this.calroies/this.mass | |
} | |
//Test Code | |
it("should return calories per gram", ()=>{ | |
/* | |
Run some code for setting calories and mass in the object | |
Everytime we will change how calories and mass are initiated, we may need to change the test as well | |
*/ | |
assert.eq(SomeService.getCaloriesPerGram(), 100); | |
}) | |
//instead | |
SomeService.getCaloriesPerGram(calories, mass) { | |
return calroies/mass | |
} | |
//Test Code | |
it("should return calories per gram", ()=>{ | |
/* | |
No need to change everytime. | |
*/ | |
assert.eq(SomeService.getCaloriesPerGram(10000, 100), 100); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment