This repository has been archived by the owner on Aug 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
waitForCondition.js
72 lines (60 loc) · 2.37 KB
/
waitForCondition.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var util = require('util'),
events = require('events');
var CommandAction = function() {
events.EventEmitter.call(this);
this.startTimer = null;
this.cb = null;
this.ms = null;
this.selector = null;
this.protocol = require('nightwatch/lib/api/protocol.js')(this.client);
};
util.inherits(CommandAction, events.EventEmitter);
CommandAction.prototype.command = function(condition, milliseconds, timeout, messages, callback) {
if (milliseconds && typeof milliseconds !== 'number') {
throw new Error('waitForCondition expects second parameter to be number; ' + typeof (milliseconds) + ' given');
}
var lastArgument = Array.prototype.slice.call(arguments, 0).pop();
if (typeof (lastArgument) === 'function') {
callback = lastArgument;
}
if (!messages || typeof messages !== 'object') {
messages = {
success: 'Condition was satisfied after ',
timeout: 'Timed out while waiting for condition after '
};
}
timeout = timeout && typeof (timeout) !== 'function' && typeof (timeout) !== 'object' ? timeout : 0;
this.startTimer = new Date().getTime();
this.cb = callback || function() {
};
this.ms = milliseconds || 1000;
this.timeout = timeout;
this.condition = condition;
this.messages = messages;
this.check();
return this;
};
CommandAction.prototype.check = function() {
var self = this;
this.protocol.execute.call(this.client, this.condition, function(result) {
var now = new Date().getTime();
if (result.status === 0 && result.value !== 'undefined') {
setTimeout(function() {
var msg = self.messages.success + (now - self.startTimer) + ' milliseconds.';
self.cb.call(self.client.api, result.value);
self.client.assertion(true, !!result.value, false, msg, true);
return self.emit('complete');
}, self.timeout);
} else if (now - self.startTimer < self.ms) {
setTimeout(function() {
self.check();
}, 500);
} else {
var msg = self.messages.timeout + self.ms + ' milliseconds.';
self.cb.call(self.client.api, false);
self.client.assertion(false, false, false, msg, true);
return self.emit('complete');
}
});
};
module.exports = CommandAction;