How to spy nested function call

4,572 views
Skip to first unread message

hellboy

unread,
Feb 18, 2015, 4:33:45 PM2/18/15
to sin...@googlegroups.com
Assume db is mongo instance (or implements its interface)

I can create spy for call of collection method with

var colSpy = sinon.spy(db, 'collection')


How can I create spy for this call:

db.collection(myColName).update(..., ...)






Christian Johansen

unread,
Feb 19, 2015, 2:35:30 AM2/19/15
to sin...@googlegroups.com
var colSpy = sinon.stub(db, 'collection').returns({update: sinon.spy()});

You should be careful with nesting stuff too deeply, as it removes your test code from reality with no way to check that reality and your stubs are consistent.

C

--
You received this message because you are subscribed to the Google Groups "Sinon.JS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sinonjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
MVH
Christian

hellboy

unread,
Feb 19, 2015, 10:37:15 AM2/19/15
to sin...@googlegroups.com, chri...@cjohansen.no
Your code also override collection method with stub.

As I mentioned you suggests to create stubs/mocks  for db manually and do not use in-memory imitation of MongoDB database?

P.S. I am wondering I cannot find the right way to test module functions that uses database

As I mentioned there are 3 ways to verify test result:
1) Call another (potentially) your module function. Wrong: Your checks should never depends on untested code. Should not be used. Isn't it?
2) Call db functions directly to check if database state has been changed correctly. Right: your are using tested code. This code is not yours. It's easy to test UPDATEs and DELETEs But: How to tests INSERTs?
3) Check (with spy?) if database method has been called. If you tested method has

As I mentioned 3) is the best solution. If your method has only GET or SET (not mixed) -> <работа метода не зависит от > -> Использование db in - memory store можен быть заменено простыми стабами.

Christian Johansen

unread,
Feb 20, 2015, 8:59:39 AM2/20/15
to sin...@googlegroups.com
Frankly I didn't understand all that. These are the two options I would consider:

1) Use in-memory database. In that case, verify tests by querying the db state
2) Use stubs. Follow my example.

1) is probably your best option.

C

Ali Shariat

unread,
Mar 3, 2015, 1:29:22 PM3/3/15
to sin...@googlegroups.com
use 
sinon.spy mongodb.Collection.prototype, "update"

hellboy

unread,
Apr 14, 2015, 2:28:47 AM4/14/15
to sin...@googlegroups.com, chri...@cjohansen.no
But with 1) we have not unit tests (also module tests), but integration test.
Only with stubs we have real unit tests. Isn't it?

hellboy

unread,
Sep 15, 2015, 3:51:08 AM9/15/15
to Sinon.JS
How can I use this stub if my SUT has mongo db dependency as init - constructor parameter?

SUT has no require('mongodb')
Reply all
Reply to author
Forward
0 new messages