Commit 6b786774 authored by Eduardo Sanz García's avatar Eduardo Sanz García Committed by Eduardo

Error when adding a handler if a channel has been created

The RPC class design requires all the handlers to be provided up-front.
Currently, adding a new handler after a channel is created has no
effect. To make more obvious this misuse, the method now throws an
error.
parent 88845500
......@@ -143,8 +143,15 @@ export default class Bridge {
* callback of the type: `(error: string|Error|null, ...result: any[]) => void`.
* This callback must be invoked in order to respond (via `postMessage`)
* to the other frame/s with a result or an error.
* @throws {Error} If trying to register a callback after a channel has already been created
* @throws {Error} If trying to register a callback with the same name multiple times
*/
on(method, callback) {
if (this.links.length > 0) {
throw new Error(
`Listener '${method}' can't be registered because a channel has already been created`
);
}
if (this.channelListeners[method]) {
throw new Error(`Listener '${method}' already bound in Bridge`);
}
......
......@@ -168,14 +168,39 @@ describe('shared/bridge', () => {
describe('#on', () => {
it('adds a method to the method registry', () => {
createChannel();
bridge.on('message1', sandbox.spy());
createChannel();
assert.isFunction(bridge.channelListeners.message1);
});
it('raise an error if trying to register a listener after a channel has been already created', () => {
createChannel();
let error;
try {
bridge.on('message1', () => {});
} catch (err) {
error = err;
}
assert.equal(
error.message,
"Listener 'message1' can't be registered because a channel has already been created"
);
});
it('only allows registering a method once', () => {
bridge.on('message1', sandbox.spy());
assert.throws(() => bridge.on('message1', sandbox.spy()));
bridge.on('message1', () => {});
let error;
try {
bridge.on('message1', () => {});
} catch (err) {
error = err;
}
assert.equal(
error.message,
"Listener 'message1' already bound in Bridge"
);
});
});
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment