How to simulate an 'error' event on MongoD

2019-07-15 13:11发布

问题:

I'm trying to write a test case for a NoFlo component (written by a colleague) - where the component has a "connect" inPort and an "error" outPort like:

var self = this; // a NoFlo Component
var mongodb = null;

self.inPorts.connect.on("data", function(uri) {
    mongodb = mongojs(uri);

    self.outPorts.connected.send(mongodb);

    mongodb.on("error", function(error) {
        self.outPorts.error.send(error);
    });
});

So based on this code pattern, how should I simulate an erroneous situation (in the test case) so that it sends an error through the outPort?

I tried sending a bad uri like "lcalhost:99999/abcdef", but it doesn't work.


Update: the original code sends the mongodb instance through a "connected" outPort, I cached it to emit the "error" event successfully.

回答1:

mongojs extends EventEmitter.

Assuming mongodb is global, call mongodb.emit("error", "This is an error") to activate the error event.

If mongodb is undefined, try using the value of self to get access to it.

More info:

  • http://nodejs.org/api/events.html#events_emitter_emit_event_arg1_arg2
  • https://github.com/mafintosh/mongojs/blob/master/index.js
  • http://cjohansen.no/talks/2011/xp-meetup/#70