Background
I have a server that registers some RPCs using crossbar, and a test that is trying to make sure that the RPCs are being called using sinon.
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();
} );
//removing Object.freeze won't help =(
return Object.freeze({
start,
open
});
};
module.exports = server;
This server simply connects to the crossbar and then registers the open
RPC.
Now my test case. I am using 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 opens a connection to the crossbar as well and then calls the open
method on the server.
Problem
The problem is that even though I see the Hello World
console.log, proving that the method was in fact executed, my test always fails because of the openSpy.called
is always false
(even though the spied method was called!).
What I tried
- Removing
Object.freeze
. I understand spies and stubs actually replace the functions and objects they are spying on, but in this case, it didn't help. - Using a
stub
instead of aspy
. When my spy didn't work, I tried replacing theopen
method with astub
and use thecallsFake
to finish the test. UnfortunatelycallsFake
never seems to be called ... - Using
setTimeout
. I thought that perhaps the reason this was happening was that I am making the test to soon, so I created asetTimeout
with0
evolving theexpect
statement. Also failed.
Question
- What am I doing wrong?
- How can I fix it?