Sometimes you need an instance method for your application, like if you see a server-level error such as this:
This server test expects an increase to the dinosaur count
, which is a responsibility of the Dinosaur model. You’ll need to drop to the model layer and test for a .breed()
method.
.breed()
will increase the count
of one dinosaur. This kind of method is specific to an instance of a model, so you’ll need to define it as an instance method. Do this by storing it in [schema].methods
as shown below.
// instance method - implementation DinosaurSchema.methods.breed = function() { this.count = this.count + 1; }; // instance method - call the method dino.breed()
Use function()
notation instead of arrow =>
notation to properly bind this
.
You can test-drive the development of this method just like any other JavaScript method: Call the method and make assertions on its output.
Instructions
In dinosaur-test.js under it('increases count by 1'
(scroll to the bottom of the file) add the following setup:
const start = 3; const end = 4; const dino = new Dinosaur({ name: 'Stegosaurus', count: start, risk: 'Low' });
Call dino.breed()
.
Assert that dino.count
is strictly equal to end
.
Run npm test
and see the error message
TypeError: dino.breed is not a function
In dinosaur.js, define an empty breed
method in DinosaurSchema.methods
.
Use function() {}
notation.
Run npm test
and see the error message
AssertionError: expected 3 to equal 4
In dinosaur.js, add the implementation code provided in the narrative above.
Run npm test and see green!