I've written a test that should be failing.
I'm using Mocky.io to mock my API response.
When I run an API response test with Supertest & Mocha and launch the test with WebdriverIO, it does not fail (I expect it to fail!!).
If I run the same test directly with the Mocha framework, it does fail (as expected).
Here is my code.
The test:
const request = require('supertest');
const { expect } = require('chai');
describe('TEST', () => {
it('Mocky OK response', (done) => {
request('https://run.mocky.io')
.get('/v3/dde9652d-d744-4946-8a2e-c18ec7b34a59AAAAA')
.expect(200, done);
});
it('Mocky 500 response', (done) => {
request('https://run.mocky.io')
.get('/v3/4fc6a0e6-264e-4d84-bc40-a369a24ff519')
.expect(200, done);
});
});
In the first IT block, I've added AAAAA to the end of the URL, so it returns 404 not found.
In the second IT block, I expect 200 OK, but the mocky API has been set up to return 500.
So both tests should fail!
When I run this code with WebdriverIO, both tests are passed.
npm run test -- --spec test.js
A snippet from package.json
"scripts": {
"test": "./node_modules/.bin/wdio wdio.conf.js",
When I run this code with Mocha, both tests are failed (This is what I want)
./node_modules/mocha/bin/mocha test.js
So, somehow WebdriverIO: ignores the assertion? changes the response?
Here is my wdio.conf file.
exports.config = {
//
// ====================
// Runner Configuration
// ====================
//
// WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
// on a remote machine).
runner: 'local',
//
// ==================
// Specify Test Files
// ==================
// Define which test specs should run. The pattern is relative to the directory
// from which `wdio` was called. Notice that, if you are calling `wdio` from an
// NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
// directory is where your package.json resides, so `wdio` will be called from there.
//
specs: ['./test/**/*.js'],
suites: {
testLoginPage: ['./test/testLoginPage/*'],
testAddressPage: ['./test/testAddressPage/*'],
testUsermenuForm: ['./test/testUsermenuForm/*'],
testCreateAddressForm: ['./test/testCreateAddressForm/*'],
},
// Patterns to exclude.
exclude: [
// 'path/to/excluded/files'
],
//
// ============
// Capabilities
// ============
// Define your capabilities here. WebdriverIO can run multiple capabilities at the same
// time. Depending on the number of capabilities, WebdriverIO launches several test
// sessions. Within your capabilities you can overwrite the spec and exclude options in
// order to group specific specs to a specific capability.
//
// First, you can define how many instances should be started at the same time. Let's
// say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
// set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
// files and you set maxInstances to 10, all spec files will get tested at the same time
// and 30 processes will get spawned. The property handles how many capabilities
// from the same test should run tests.
//
maxInstances: 10,
//
// If you have trouble getting all important capabilities together, check out the
// Sauce Labs platform configurator - a great tool to configure your capabilities:
// https://docs.saucelabs.com/reference/platforms-configurator
//
capabilities: [
{
// maxInstances can get overwritten per capability. So if you have an in-house Selenium
// grid with only 5 firefox instances available you can make sure that not more than
// 5 instances get started at a time.
maxInstances: 5,
//
// browserName: 'chrome',
browserName: 'chrome',
'goog:chromeOptions': {
args: ['--window-size=1920,1080', '--disable-infobars'].concat(
(function () {
return process.env.HEADLESS_CHROME === '1'
? [
'--headless',
'--no-sandbox',
'--disable-gpu',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
]
: [];
})()
),
},
acceptInsecureCerts: true,
// If outputDir is provided WebdriverIO can capture driver session logs
// it is possible to configure which logTypes to include/exclude.
// excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
// excludeDriverLogs: ['bugreport', 'server'],
},
],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity: trace | debug | info | warn | error | silent
logLevel: 'warn',
//
// Set specific log levels per logger
// loggers:
// - webdriver, webdriverio
// - #wdio/applitools-service, #wdio/browserstack-service, #wdio/devtools-service, #wdio/sauce-service
// - #wdio/mocha-framework, #wdio/jasmine-framework
// - #wdio/local-runner
// - #wdio/sumologic-reporter
// - #wdio/cli, #wdio/config, #wdio/sync, #wdio/utils
// Level of logging verbosity: trace | debug | info | warn | error | silent
// logLevels: {
// webdriver: 'info',
// '#wdio/applitools-service': 'info'
// },
//
// If you only want to run your tests until a specific amount of tests have failed use
// bail (default is 0 - don't bail, run all tests).
bail: 0,
//
// Set a base URL in order to shorten url command calls. If your `url` parameter starts
// with `/`, the base url gets prepended, not including the path portion of your baseUrl.
// If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
// gets prepended directly.
baseUrl: url[process.env.ENV],
//
// Default timeout for all waitFor* commands.
waitforTimeout: 5000,
//
// Default timeout in milliseconds for request
// if browser driver or grid doesn't send response
connectionRetryTimeout: 120000,
//
// Default request retries count
connectionRetryCount: 3,
//
// Test runner services
// Services take over a specific job you don't want to take care of. They enhance
// your test setup with almost no effort. Unlike plugins, they don't add new
// commands. Instead, they hook themselves up into the test process.
services: ['selenium-standalone', 'intercept'],
// Framework you want to run your specs with.
// The following are supported: Mocha, Jasmine, and Cucumber
// see also: https://webdriver.io/docs/frameworks
//
// Make sure you have the wdio adapter package for the specific framework installed
// before running any tests.
framework: 'mocha',
//
// The number of times to retry the entire specfile when it fails as a whole
// specFileRetries: 1,
//
// Delay in seconds between the spec file retry attempts
// specFileRetriesDelay: 0,
//
// Whether or not retried specfiles should be retried immediately or deferred to the end of the queue
// specFileRetriesDeferred: false,
//
// Test reporter for stdout.
// The only one supported by default is 'dot'
// see also: https://webdriver.io/docs/dot-reporter
reporters: ['spec'],
//
// Options to be passed to Mocha.
// See the full list at http://mochajs.org/
mochaOpts: {
ui: 'bdd',
timeout: 60000,
},
//
// =====
// Hooks
// =====
// WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
// it and to build services around it. You can either apply a single function or an array of
// methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
// resolved to continue.
/**
* Gets executed once before all workers get launched.
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
*/
// onPrepare: function (config, capabilities) {
// },
/**
* Gets executed before a worker process is spawned and can be used to initialise specific service
* for that worker as well as modify runtime environments in an async fashion.
* #param {String} cid capability id (e.g 0-0)
* #param {[type]} caps object containing capabilities for session that will be spawn in the worker
* #param {[type]} specs specs to be run in the worker process
* #param {[type]} args object that will be merged with the main configuration once worker is initialised
* #param {[type]} execArgv list of string arguments passed to the worker process
*/
// onWorkerStart: function (cid, caps, specs, args, execArgv) {
// },
/**
* Gets executed just before initialising the webdriver session and test framework. It allows you
* to manipulate configurations depending on the capability or spec.
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that are to be run
*/
// beforeSession: function (config, capabilities, specs) {
// },
/**
* Gets executed before test execution begins. At this point you can access to all global
* variables like `browser`. It is the perfect place to define custom commands.
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that are to be run
* #param {Object} browser instance of created browser/device session
*/
// before: function (capabilities, specs) {
// },
/**
* Runs before a WebdriverIO command gets executed.
* #param {String} commandName hook command name
* #param {Array} args arguments that command would receive
*/
// beforeCommand: function (commandName, args) {
// },
/**
* Hook that gets executed before the suite starts
* #param {Object} suite suite details
*/
// beforeSuite: function (suite) {
// },
/**
* Function to be executed before a test (in Mocha/Jasmine) starts.
*/
beforeTest() {
const chai = require('chai');
const chaiWebdriver = require('chai-webdriverio').default;
chai.use(chaiWebdriver(browser));
global.assert = chai.assert;
global.should = chai.should;
global.expect = chai.expect;
// browser.maximizeWindow();
// browser.setWindowSize(1920, 1080);
},
/**
* Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling
* beforeEach in Mocha)
*/
// beforeHook: function (test, context) {
// },
/**
* Hook that gets executed _after_ a hook within the suite starts (e.g. runs after calling
* afterEach in Mocha)
*/
// afterHook: function (test, context, { error, result, duration, passed, retries }) {
// },
/**
* Function to be executed after a test (in Mocha/Jasmine).
*/
// afterTest: function(test, context, { error, result, duration, passed, retries }) {
// },
/**
* Hook that gets executed after the suite has ended
* #param {Object} suite suite details
*/
// afterSuite: function (suite) {
// },
/**
* Runs after a WebdriverIO command gets executed
* #param {String} commandName hook command name
* #param {Array} args arguments that command would receive
* #param {Number} result 0 - command success, 1 - command error
* #param {Object} error error object if any
*/
// afterCommand: function (commandName, args, result, error) {
// },
/**
* Gets executed after all tests are done. You still have access to all global variables from
* the test.
* #param {Number} result 0 - test pass, 1 - test fail
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that ran
*/
// after: function (result, capabilities, specs) {
// },
/**
* Gets executed right after terminating the webdriver session.
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
* #param {Array.<String>} specs List of spec file paths that ran
*/
// afterSession: function (config, capabilities, specs) {
// },
/**
* Gets executed after all workers got shut down and the process is about to exit. An error
* thrown in the onComplete hook will result in the test run failing.
* #param {Object} exitCode 0 - success, 1 - fail
* #param {Object} config wdio configuration object
* #param {Array.<Object>} capabilities list of capabilities details
* #param {<Object>} results object containing test results
*/
// onComplete: function(exitCode, config, capabilities, results) {
// },
/**
* Gets executed when a refresh happens.
* #param {String} oldSessionId session ID of the old session
* #param {String} newSessionId session ID of the new session
*/
// onReload: function(oldSessionId, newSessionId) {
// }
};
I am using Suitescript 2.0. There I am trying to reschedule a script for a particular type of error.
I got the below code which can be used to rescheduled the script immediately.
var scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask.scriptId = 'customscript_id';
scriptTask.deploymentId = 'customdeploy_id';
var scriptTaskId = scriptTask.submit();
But I am mainly looking for some option to run it after a certain time like after an hour.
Is it possible to achieve by passing any kind of parameter to the above task?
Any other alternative approach would also helpful.
I had a similar issue, I needed to delay my schedule a certain time in your case a map/reduce script which should be the same.
I fixed it with this approach.
Here is sample code with the approach.
/**
#NApiVersion 2.x
#NScriptType ScheduledScript
#NModuleScope SameAccount
*/
define(['N/file', 'N/record', 'N/render', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/format', 'N/task', 'N/log'],
function(file, record, render, runtime, search, serverWidget, format, task, log) {
/**
* Definition of the Scheduled script trigger point.
*
* #param {Object} scriptContext
* #param {string} scriptContext.type - The context in which the script is executed. It is one of the values from the scriptContext.InvocationType enum.
* #Since 2015.2
*/
function execute(scriptContext) {
wait(20000); // it waits 20 sec
//whatever you want to do
}
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
return {
execute: execute
};
});
I'm using Expressjs
At /routes/index.js i have:
app.group('/test', test => {
const testHandler = new testHandler();
test.get('/test-action', testHandler.testAction.bind(testHandler));
});
At /test/handler.js i have
export class testHandler {
constructor() {
}
/**
* #param req
* #param res
* #param next
* #returns {*}
*/
async testAction(req, res, next) {
// todo code here
}
}
I want to create a cronjob to run that route ( for example localhost:3000/test/test-action ) twice an hour.
With PHP i can do it by * */2 * * * php /path_to_webroot/index.php param1 param2
Is there a similar way to do it with Nodejs?
You can use node-cron. It uses similar syntax as you are using in php.
# min hour mday month wday command
*/15 * * * * some-command
to schedule some-command to run every 15 minutes, node-cron would use a similar syntax to specify the time to run:
'0 */15 * * * *'
Well, you need to define your express routes normally. Then inside your cron function you would make a request to that express route you have defined.
request('http://localhost:3000/test/test-action', function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('im ok')
// console.log(body)
}
})
You can use `request inside your corn job. This way your API will get called every specific time.
In my electron application I create Diffie-Hellman keys via the following method:
const crypto = require('crypto');
/**
* Generate the keys and the diffie hellman key agreement object.
* #param {Integer} p The prime for Diffie Hellman Key Generation
* #param {Integer} g The generator for Diffie Hellman Key Exchange
*/
async function createSelfKey(p, g, callback) {
let returnVal = null;
if (p && g) {
returnVal = { dh: await crypto.createDiffieHellman(p, g) };
} else {
returnVal = { dh: await crypto.createDiffieHellman(2048) };
}
returnVal.keys = await returnVal.dh.generateKeys();
return callback(returnVal);
};
But the key generation is a slightly computation-heavy process thus it makes my application to freeze. An example of usage is when I try to implement this method generateCreatorKeys from the following function:
function ChatRoomStatus() {
/**
* #var {Object}
*/
const chatrooms = {};
// Some other logic
/**
* This Method fetched the creator of the Chatroom and executes a callback on it.
* #param {String} chatroom The chatroom to fetch the creator
* #param {Function} callback The callback of the chatroom.
*/
this.processCreator = (chatroom, callback) => {
const index = _.findIndex(chatrooms[chatroom].friends, (friend) => friend.creator);
return callback(chatrooms[chatroom].friends[index], index , chatrooms[chatroom] );
};
/**
* Generate keys for the Chatroom Creator:
* #param {String} chatroom The chatroom to fetch the creator
* #param {Function} callback The callback of the chatroom.
*/
this.generateCreatorKeys = (chatroom, callback) => {
return this.processCreator(chatroom, (friend, index, chatroom) => {
return createSelfKey(null, null, (cryptoValues) => {
friend.encryption = cryptoValues;
return callback(friend, index, chatroom);
});
});
};
};
An example that this method is called is:
const { xml, jid } = require('#xmpp/client');
/**
* Handling the message Exchange for group Key agreement
* #param {Function} sendMessageCallback
* #param {ChatRoomStatus} ChatroomWithParticipants
*/
function GroupKeyAgreement(sendMessageCallback, ChatroomWithParticipants) {
const self = this;
/**
* Send the Owner participant Keys into the Chatroom
*/
self.sendSelfKeys = (chatroomJid, chatroomName) => {
ChatroomWithParticipants.generateCreatorKeys(chatroomName, (creator) => {
const message = xml('message', { to: jid(chatroomJid).bare().toString()+"/"+creator.nick });
const extention = xml('x', { xmlns: 'http://pcmagas.tk/gkePlusp#intiator_key' });
extention.append(xml('p', {}, creator.encryption.dh.getPrime().toString('hex')));
extention.append(xml('g', {}, creator.encryption.dh.getGenerator().toString('hex')));
extention.append(xml('pubKey', {}, creator.encryption.keys.toString('hex')));
message.append(extention);
sendMessageCallback(message);
});
};
};
module.exports = GroupKeyAgreement;
Do you know how I can "run" the function createSelfKey in parallel/seperate thread and serve its contents via a callback? Also the code above runs on Electron's main process thus a freeze on it causes the whole application to stall for a while.
I'd take a look at https://electronjs.org/docs/tutorial/multithreading.
Electron has basically everything from the DOM and node.js plus more in it, so you have a few options. In general, they are:
Web workers (renderer process only). If you're doing this in a renderer process, you can just use plain DOM web workers. Those are run in a separate process or thread (not sure which, that's a chromium implementation detail, but it definitely won't block your UI).
It looks like node.js worker_threads (renderer process only?) are also available now in Electron. That might work as well, never used these personally.
You can always create another renderer process and use that as your separate "thread" and communicate with it via IPC. When the work is done, you just close that. You do this by creating a new, hidden BrowserWindow.
Use node.js' cluster/child_process module to spin up a new node process, and use it's built-in IPC (not Electron's) to communicate with it.
Because you're running this code in the main process and assuming you can't move it out, your only option (to my knowledge) is #3. If you're okay with adding a library, electron-remote (https://github.com/electron-userland/electron-remote#the-renderer-taskpool) has some cool functionality that let's you spin up a renderer process (or several) in the background, get the results as a promise, and then closes them for you.
The best solution I tried to your problem is the following code based upon answer:
const crypto = require('crypto');
const spawn = require('threads').spawn;
/**
* Generate the keys and the diffie hellman key agreement object.
* #param {Integer} p The prime for Diffie Hellman Key Generation
* #param {Integer} g The generator for Diffie Hellman Key Exchange
* #param {Function} callback The callback in order to provide the keys and the diffie-hellman Object.
*/
const createSelfKey = (p, g, callback) => {
const thread = spawn(function(input, done) {
const cryptot = require('crypto');
console.log(input);
const pVal = input.p;
const gVal = input.g;
let dh = null;
if (pVal && gVal) {
dh = cryptot.createDiffieHellman(pVal, gVal);
} else {
dh = cryptot.createDiffieHellman(2048);
}
const pubKey = dh.generateKeys();
const signaturePubKey = dh.generateKeys();
done({ prime: dh.getPrime().toString('hex'), generator: dh.getGenerator().toString('hex'), pubKey, signaturePubKey});
});
return thread.send({p,g}).on('message', (response) => {
callback( crypto.createDiffieHellman(response.prime, response.generator), response.pubKey, response.signaturePubKey);
thread.kill();
}).on('error', (err)=>{
console.error(err);
}).on('exit', function() {
console.log('Worker has been terminated.');
});
};
As you can see using the threads library from npm will provide you what you need. The only negative on this approach is that you cannot pass the in-thread generated objects outside the thread's scope. Also the code that is inside the function executing the thread is an some sort of an isolated one thus you may need to re-include any library you need as you can see above.
I am running into the issue below when trying to edit a CUSTOMER record in NetSuite. The script I have created is very simple.
What could I possibly doing wrong with such a simplistic piece of code?
{"type":"error.SuiteScriptModuleLoaderError","name":"MODULE_DOES_NOT_EXIST","message":"Module does not exist: /SuiteScripts/BillingInfoUpdated.js","stack":[]}
SCRIPT:
define(['N/log'], function (log) {
/**
* User Event 2.0 example showing usage of the Submit events
*
* #NApiVersion 2.x
* #NModuleScope SameAccount
* #NScriptType UserEventScript
* #appliedtorecord customer
*/
var exports = {};
function afterSubmit(scriptContext) {
log.debug({
"title": "After Submit",
"details": "action=" + scriptContext.type
});
}
exports.afterSubmit = afterSubmit;
return exports;
});
Add .js to the end of the script file name
Nathan Sutherland answer worked for me and it's absolutely fine But I'm writing this answer so new user get that faster and not confused with other names.
You need to add .js where the blue arrow points.
On starting while creating script.
if you forget then edit here
Use this instead:
var LOGMODULE; //Log module is preloaded, so this is optional
/**
*#NApiVersion 2.x
*#NModuleScope Public
*#NScriptType UserEventScript
*/
define(['N/log'], runUserEvent);
function runUserEvent(log) {
LOGMODULE = log;
var returnObj = {};
returnObj.afterSubmit = afterSubmit;
return returnObj;
}
function afterSubmit(context) {
log.debug('After Submit', "action=" + context.type);
//LOGMODULE.debug('After Submit', "action=" + context.type); //Alternatively
//context.newRecord; //Just showing how to access the records
//context.oldRecord;
//context.type;
return;
}
For more 2.0 Quickstart Samples: ursuscode.com