Skip to content

Commit

Permalink
adds .once() and .removeListener(), fixes #663
Browse files Browse the repository at this point in the history
  • Loading branch information
rosshinkley committed May 27, 2016
1 parent 1f03809 commit 454f526
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 1 deletion.
6 changes: 6 additions & 0 deletions Readme.md
Expand Up @@ -318,6 +318,12 @@ Listen for `console.log(...)`, `console.warn(...)`, and `console.error(...)`.
###### .on('console', function(type, errorMessage, errorStack))
This event is triggered if `console.log` is used on the page. But this event is not triggered if the injected javascript code (e.g. via `.evaluate()`) is using `console.log`.

#### .once(event, callback)
Similar to `.on()`, but captures page events with the callback one time.

#### .removeListener(event, callback)
Removes a given listener callback for an event.

#### .screenshot([path][, clip])
Takes a screenshot of the current page. Useful for debugging. The output is always a `png`. Both arguments are optional. If `path` is provided, it saves the image to the disk. Otherwise it returns a `Buffer` of the image data. If `clip` is provided (as [documented here](https://github.com/atom/electron/blob/master/docs/api/browser-window.md#wincapturepagerect-callback)), the image will be clipped to the rectangle.

Expand Down
18 changes: 18 additions & 0 deletions lib/nightmare.js
Expand Up @@ -348,6 +348,24 @@ Nightmare.prototype.on = function(event, handler) {
return this;
};

/**
* once
*/

Nightmare.prototype.once = function(event, handler) {
this.child.once(event, handler);
return this;
};

/**
* removeEventListener
*/

Nightmare.prototype.removeListener = function(event, handler) {
this.child.removeListener(event, handler);
return this;
};

/**
* Queue
*/
Expand Down
39 changes: 38 additions & 1 deletion test/index.js
Expand Up @@ -1037,7 +1037,7 @@ describe('Nightmare', function () {
});
});

describe('events', function () {
describe.only('events', function () {
var nightmare;

beforeEach(function() {
Expand Down Expand Up @@ -1154,6 +1154,43 @@ describe('Nightmare', function () {
confirm.should.equal('my confirm');
response.should.equal('hello!');
});

it('should only fire once when using once', function*() {
var events = 0;
nightmare.once('page', function(type, message) {
events++;
});

yield nightmare
.goto(fixture('events'))
events.should.equal(1);
});

it('should remove event listener', function*() {
var events = 0;
var handler = function(type, message) {
if (type === 'alert') {
events++;
}
};

nightmare.on('page', handler);

yield nightmare
.goto(fixture('events'))
.evaluate(function(){
alert('alert one');
});

nightmare.removeListener('page', handler);

yield nightmare
.evaluate(function(){
alert('alert two');
});

events.should.equal(1);
});
});

describe('options', function () {
Expand Down

0 comments on commit 454f526

Please sign in to comment.