Learn
Model Testing Patterns
Methods II

Sometimes you need an instance method for your application, like if you see a server-level error such as this:

TypeError: Dinosaur.findByName is not a function

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

1.

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' });
2.

Call dino.breed().

3.

Assert that dino.count is strictly equal to end.

4.

Run npm test and see the error message

TypeError: dino.breed is not a function
5.

In dinosaur.js, define an empty breed method in DinosaurSchema.methods.

Use function() {} notation.

6.

Run npm test and see the error message

AssertionError: expected 3 to equal 4
7.

In dinosaur.js, add the implementation code provided in the narrative above.

8.

Run npm test and see green!

Folder Icon

Sign up to start coding

Already have an account?