Background
I have a server that registers some RPCs using the crossbar and a test that tries to make sure that the RPCs are called using synon.
code
server.js
"use strict"; const autobahn = require( "autobahn" ); const server = () => { const open = () => console.log( "Hello world" ); const start = () => new Promise( fulfil => { const connection = new autobahn.Connection( { "url": "ws://localhost:8080/ws", "realm": "realm1" } ); connection.onopen = session => { session.register( "server.open", open ) .then(() => fulfil()) .catch(console.log); }; connection.open(); } );
This server simply connects to the crossbar and then registers RPC open .
Now my test case. I use mocha with chai:
test.js
"use strict"; const expect = require( "chai" ) .expect; const autobahn = require( "autobahn" ); const sinon = require( "sinon" ); const serverFactory = require( "./server.js" ); describe( "server", () => { const server = serverFactory(); const crossbar = { connection: undefined, session: undefined }; const connectToCrossbar = () => new Promise( fulfil => { crossbar.connection = new autobahn.Connection({ "url": "ws://localhost:8080/ws", "realm": "realm1" }); crossbar.connection.onopen = session => { crossbar.session = session; fulfil(); }; crossbar.connection.open(); } ); before( "start server", done => { server.start() .then( connectToCrossbar ) .then( done ) .catch( err => done( err ) ); } ); it( "should open", done => { const openSpy = sinon.spy( server, "open" ); crossbar.session.call( "server.open", [] ) .then( () => { expect( openSpy.called ).to.be.true; done(); } ) .catch( err => done( err ) ); } ); } );
This test also opens a connection to the crossbar and then calls the open method on the server.
Problem
The problem is that although I see Hello World console.log, proving that the method is actually executed, my test always fails because openSpy.called always false (although the spied method was called!).
What i tried
- Uninstall
Object.freeze . I understand that spies and stubs actually replace the functions and objects that they monitor, but in this case it did not help. - Using
stub instead of spy . When my spy was not working, I tried replacing the open method with stub and using callsFake to complete the test. Unfortunately, callsFake never called ... - Using
setTimeout . I thought that maybe the reason is that I am doing the test soon, so I created setTimeout from 0 , developing the expect statement. Also failed.
Question
- What am I doing wrong?
- How can i fix this?
source share