Unit testing for loopback model
Asked Answered
T

1

7

I have a Loopback API with a model Student.

How do I write unit tests for the node API methods of the Student model without calling the REST API? I can't find any documentation or examples for testing the model through node API itself.

Can anyone please help?

Trexler answered 27/9, 2016 at 7:57 Comment(1)
For context: the Strongloop docs don't really explain testing apparently and googling for "strongloopjs test" only yields articles like this one: strongloop.com/strongblog/how-to-test-an-api-with-node-js which test the app using the HTTP API, rather than doing unit tests of the models themselves.Cheder
T
7

Example with testing the count method

// With this test file located in ./test/thistest.js

var app = require('../server');

describe('Student node api', function(){
  it('counts initially 0 student', function(cb){
      app.models.Student.count({}, function(err, count){
        assert.deepEqual(count, 0);
      });
  });
});

This way you can test the node API, without calling the REST API.

However, for built-in methods, this stuff is already tested by strongloop so should pretty useless to test the node API. But for remote (=custom) methods it can still be interesting.

EDIT: The reason why this way of doing things is not explicited is because ultimately, you will need to test your complete REST API to ensure that not only the node API works as expected, but also that ACLs are properly configured, return codes, etc. So in the end, you end up writing 2 different tests for the same thing, which is a waste of time. (Unless you like to write tests :)

Transfix answered 27/9, 2016 at 14:5 Comment(4)
Thanks for your answer, but there is one issue with the code given above. For unit testing, i dont wanna use my actual db. i wanna use in memory db. So in that case how to create in memory data? and how to add users, access tokens in in-memory db?? Also i wanna use beforeEach hook to insert records in Student table. So that i can get some count value. Hope this explains more about my issue.Trexler
Could not guess it from the question, but creating an in-memory database is very easy (see here). And it is transparent for you, whether you use memory or a true db.Transfix
And to add users, access tokens, etc. you just use the node API that is documented in the link I've given. Here it is again : apidocs.strongloop.comTransfix
And in case you were wondering, you can use the in-memory database for testing, and switch to a true database in production (this is documented hereTransfix

© 2022 - 2024 — McMap. All rights reserved.