Right now i have grunt setup to watch for file changes and feed them to mocha, and mocha runs the tests. The problem is when modules include something like "nw.gui" the test case cannot find them. Is there any way to get around that, some way that i can include it?
//indexeddb.spec.js
var assert = require("assert");
var IndexedDB = require("../scripts/indexeddb");
db = new IndexedDB();
console.log(db);
describe('IndexedDB', function(){
describe('initialize', function(){
it('Should throw an error when the paramaters are null', function(){
expect(db.initialize()).to.throwError();
});
});
});
//indexeddb.js
module.exports = exports = function(){
var indexedDB = require("nw.gui").Window.get().window.indexedDB;
var _ = require("../bower_components/underscore/underscore.js")
this.initialize = function(databaseName,version,schema) {
}
}
Should i do this differently? I did think about running the tests in a gui window in webkit, but that would require that i include all the spec file's on the page and reload the page every time i wanted to run the test. With grunt and watch i was trying to get it to run the test for each file when i edited either the spec or the src file.
I will also need to test the html/js/backbone pages that i open in a webkit window.
Thanks for any insight.
Code example at https://github.com/varunvairavan/node-webkit-unit-testing
Found a way to run test's on node webkit, with a watch to reload the page on file changes.
I was going through this post https://github.com/visionmedia/mocha/issues/960 when i found a link to https://github.com/BenoitZugmeyer/chwitt/tree/5f9bc6c0b8c0328f1dc06a554e9fdd3a969c36ae/tests
The way it works is, create a new node webkit app in your test directory, it then includes all the files in that directory that end with .spec.js and runs the tests in them. It also does a page reload on file changes in the source/test folder.
I had my files in sub directories in the test folder so i used the walk function from node.js fs.readdir recursive directory search to find all the files ending with ".spec.js".
Related
So I'm currently trying to automate uploading a profile photo on an Electron App using Playwright and I'm running into issues with 'filechooser' event.
await windowA.click('data-testid');
const [fileChooser] = await Promise.all([
windowA.waitForEvent('filechooser'),
// windowA.locator('text=Edit').click(),
windowA.waitForTimeout(3000),
windowA.locator(selector).click(),
]);
The element used to upload a photo isn't an input type so I'm using
await fileChooser.setFiles(
[filepath],
{ timeout: 1000 }
);
The issue is trying to get playwright to select an image from the input dialog box that pops up and it just won't select any files. I've also been trying to get playwright to select an image in my fixtures folder, which is in a relative path to the test, but haven't had success in either case.
The error that Playwright is displaying is
page.waitForEvent: Timeout while waiting for event "filechooser"
waiting for event "filechooser"
Any know what the issue is?
My slippers told me that if you are using the window.showOpenFilePicker() to get a file from the user, you won't get the filechooser event at all. This is because internally, the showOpenFilePicker is not triggering an event as it is still a WIP.
More infos can be found there but I don't think there is a workaround for now
https://githubmemory.com/repo/microsoft/playwright/issues/8850
Pupetter has actually the same issue: https://github.com/puppeteer/puppeteer/issues/5210`
One fix would be to not use the showOpenFilePicker() at all, but instead rely on the <input> element to gather the file. This is a bit more cumbersome for the dev but is more supported and should trigger the 'filechooser' event.
Another fix could be to add a function you can override when running in test move for it to not even need to open the file chooser. Something like
getFileFromPicker() => {
if(!isRunningInTest) {
// do the showOpenFilePicker logic as usual in the app and the user will need to choose a file from it
} else {
// provide synchronously a buffer to use as file content, and so do not even show the picker to the testing user.
}
In PhpStorm/WebStorm how can I add a custom library so that the file compiles? In my case it would be Lodash?
I tried to add lodash to global libs but it did not help...
Using require and relative paths.
Here is a crazy example of using lodash in a scratch file:
const _ = require('./../../../DEV/node_modules/lodash');
var anything = [1, 2];
_.map(anything, function (item) {
console.log('Working >-P');
return item;
});
In fact, you can just add a package.json file to your scratches.
You could create one manually, but the following may be more practical:
Right click on any of your scratch files, then select "Open in terminal".
You'll notice that it will open the terminal directly in the folder of the scratches.
That's a folder such as C:\Users\ba\AppData\Roaming\JetBrains\WebStorm2020.2\scratches.
Since you are in the correct directory now, you can just run npm init from that terminal to create your package.json file. (You will be prompted with a bunch of questions, but you can just press enter for all questions if you are fine with the default values)
This file will just show up in your scratches along with your other files.
To answer your specific question, if you want to add lodash to those packages, you can open the terminal in the way mentioned above. This terminal will be in the correct folder. And then you can just run your npm install lodash from there.
var path = require('path');
_require = require;
require = function (p) {
var absPath = path.join(process.cwd(), p);
var relPath = path.relative(__dirname, absPath);
return _require(relPath);
}
var Query = require('./server/libs/query_builder.js');
A bit late to answer, but if you replace the require function as I show above you can use it normally.
Well I would suggest in this case to use plugin named Quokka.js available for Webstorm and other JetBrains tools.
It's recognise automatically the libraries from node_modules and have a lot of other features (work much better that pure scratch files).
When you will install it the default scratch Javascript and Typescript files will work with Quokka.
You will find the details on the official tool page: https://quokkajs.com/
Please select JET BRAINS tool on main page. Hope it helps.
I'd like to reopen the question posed here and here about testing file uploading within Nightwatch.js which uses selenium.
Both links have the recommended solution of setting the value of the file input element as the url. In my use case, I've been unable to get this to work. Even setting the value tag manually, outside of nightwatch, of the input where type="file", does not change the url. I've tried this on Chrome, Firefox, and IE10, within the dev tools.
An alternative solution I've looked at was trying to emulate the entire file upload process keystrokes. This would follow the path of clicking the file upload button, typing the path, and typing enter. This would be done through the .click and .key methods. However, you lose focus of the actual file upload window, which delays the keystrokes until that window is closed. Other developers have seemed to be able to fix this solution directly in selenium using the .findElement and .sendKeys methods in java, but I could not figure out how to do this within javascript and nightwatch itself.
Any ideas?
// My test
module.exports = {
"Standard File Upload" : function (browser) {
browser
.url("http://localhost:3000")
.waitForElementVisible('body', 1000)
.waitForElementVisible('input[type="file"]', 1000)
.setValue('input[type="file"]','http://localhost:3000/testfile.txt')
.click('#submit')
.pause(1000)
.assert.containsText('h3', 'File Uploaded Successfully')
.end();
}
};
// http://localhost:3000/testfile.txt was tested manually in the file upload window and worked successfully
<!-- My input tag -->
<input id="fileUpload" type="file" name="textfile"/>
There were two seperate issues with my setValue() method implementation.
Using the --verbose tag in the nightwatch command led me to an issue
where it was not actually finding the input tag during the
setValue(), however it was during the waitForElementVisible().
Changing input[type="file"] to input#fileUpload solved this
issue.
Secondly, the following ways of describing the path were not working...
'textfile.txt'
'http://localhost:3000/testfile.txt' (Will work if typed manually into file upload window)
What did work was using require('path').resolve(__dirname + '/testfile.txt')
Take a look here to see the discussion that led to the fix. Thanks goes out to richard-flosi.
The working code:
module.exports = {
"Standard File Upload" : function (browser) {
browser
.url("http://localhost:3000")
.waitForElementVisible('body', 1000)
.waitForElementVisible('input#fileUpload', 1000)
.pause(1000)
.setValue('input#fileUpload', require('path').resolve(__dirname + '/testfile.txt')) // Works
// .setValue('input#fileUpload', "testfile.txt") // Will not work
// .setValue('input#fileUpload', "http://localhost:3000/testfile.txt") // Will not work
// .setValue('input[type="file"]', require('path').resolve(__dirname + '/testfile.txt')) // Will not work
.click('#submit')
.pause(1000)
.assert.containsText('h3', 'File Uploaded Successfully')
.end();
}
};
I'm not sure why you're having these issues, maybe check to see if you are using the latest version of selenium server and nightwatch. This code works for me 100% in Chrome, Safari, Firefox, IE7/8/9/10/11 (not tested in IE6 but assume it as well).
driver.setValue('input#fileUpload', __dirname + '\\testfile.txt')
In my case, I had an additional problem because the file I was trying to upload was too high up in my directory structure.
As soon as I moved the file to the same level (or in a subdirectory of) the actual test files, things worked.
From a script living in my page-objects folder:
// No dice:
var fullPath = require('path').resolve(__dirname + '/../../somefile.pdf');
// Works:
var fullPath = require('path').resolve(__dirname + '/../somefile.pdf');
this.setValue('input#fileUpload', fullPath);
Follow up to this question:
apply downloaded CSS on windows 8 metroUI app
So, yes, Windows says "for security reasons, you cannot navigate to HTML you have downloaded to this location and you cannot run any executable or potentially executable code, such as script or CSS. It is intended for media such as images or videos and the like."
But I really, really want to use that css file from my local storage. Shouldn't I be able to use the execUnsafeLocalFunction method to bypass this restriction like this?:
MSApp.execUnsafeLocalFunction(function () {
el["href"] = "ms-appdata:///local/style.css"
});
It still throws "An app can’t load remote web content in the local context."
I also tried just reading the file with localFolder.getFileAsync and readText, but nothing seems to help. Is there really no way to work around this?
I think I found a way to get the CSS to load.
I tested the code below by adding a css file that sets the body background to red in the local storage folder.
The code reads the contents of the file, creates a style tag in the head and adds the content of the css file to the style.
var url = new Windows.Foundation.Uri(filename);
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function (file) {
Windows.Storage.FileIO.readTextAsync(file).then(function(text) {
var style = document.createElement("style");
style.innerText = text;
document.getElementsByTagName("head")[0].appendChild(style);
});
});
I'm not quite getting how to use PhantomJS and Mocha together, specifically through mocha-phantomjs.
I've read some tutorials (the one at tutsplus is quite helpful) and am not seeing how I can test external pages using Phantom and Mocha. I'm sure I just need a nudge.
In the tutorial the author creates a tests.js file with some DOM setup/manipulation, as well as some mocha assertions. Then, he creates a separate HTML file that loads the tests.js file and uses mocha-phantomjs to fire up phantom and run the tests.
That's where I'm a little confused, how the mochaPhantomJS.run() method actually does things behind the scenes, whether it knows to search the js file for a describe block and run all tests within, that sort of thing. I don't need chapter and verse, but a high-level summary would be ideal.
Also, if I want to test an outside page, how can I best do that? In the tutorial all the DOM investigation and testing is done on the test page. If I want to test a different page, do I change or setup my assertions differently? Should I call the PhantomJS API from those tests and point to an external site?
Mocha will run tests that have been specified in javascript that has been included in the html page that is launched. If you look at the example html page on mocha-phantomjs it expects the test definitions using describe/it calls to be in the test/mycode.js file. If you put something like
These tests are only testing what is in the main file and associated javascript, there isn't anything special that mocha-phantomjs provides to test external html files. If you want to test your own html files I think you can head in a couple of directions, I came up with these:
first option: Create a way to load the parts of you app that you want to test into the main testing html file. How to do this depends a lot on your application setup. It is probably well-suited for a modular system. Just include the javascript from your application and test it. Not so good for full-page-html tests.
second option: Open new windows with the pages to test from the main testing html file (from within phantom that is). You can open a page using window.open() just like a normal browser. I created a proof of concept like this:
describe('hello web', function () {
it('world', function (done) {
var windowReference = window.open("fileundertest.html");
// windowReference.onload didn't work for me, so I resorted to this solution
var intervalId = window.setInterval(function () {
if (windowReference.document && windowReference.document.readyState === 'complete') {
window.clearInterval(intervalId);
expect(windowReference.document.title).to.equal("File Under Test");
done();
} else {
console.log('not ready yet');
}
}, 10);
});
}
)
This solution is relatively simple, but has the same drawbacks as any page-loading solution: you never know when the page is fully initialized and have to resort to some sort of timeout/wait system to wait for the page to get into the correct state. If you want to test a lot of separate html files these delays start to add up. Additionally waiting for 'onload' on the page that I opened wouldn't work so I created my own function based on setInterval and a (non-perfect) test on the document that was being loaded. I found out there are differences in behavior between loading an html page from the filesystem and loading the same page via a web-server.
third option: Create a mocha test that you run nodejs-style from the command line, and launch phantomjs with a specific page as part of your mocha tests. This is what I'd say you need if your system really depends on html pages that are quite different from each other.
I quickly tested the third option, here is my test based on the example I found on the phantom page (which is an alternative solution to phantomjs that is used by mocha-phantomjs -- I've used neither for more than brief experiments so I cannot recommend which one to use)
'use strict';
var chai = require('chai'),
phantom = require('phantom');
var expect = chai.expect;
describe('hello node', function () {
it('world', function (done) {
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
console.log("opened google? ", status);
page.evaluate(function () { return document.title; }, function (result) {
console.log('Page title is ' + result);
ph.exit();
expect(result).to.equal("Google");
done();
});
});
});
});
});
}
)
While it is possible to test this way I'd say that maybe the overhead of the communication between the code in the phantom-world and the testing code in the nodejs world isn't worth it. You can of course move a lot of general functionality to a couple of helper functions, but you are still stuck with having to call page.evaluate() to perform specific tests on the page. The same issues with timeouts/waits as above apply.
As an aside: do already know CasperJS? Maybe it can be helpful for your setup should you choose to build something on 'plain' phantomjs.