How do i install spectron and start scripting on it? - testing

Got a recent Requirement, where i need to do Test Automation of Backend Node js application using the spectron. I would like to know what are programming skills required to approach the same

Find the Spectron documentation at https://electronjs.org/spectron
Installation
npm install --save-dev spectron
Sample test file looks like this
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
this.app = new Application({
path: electronPath,
args: [path.join(__dirname, '..')]
})
return this.app.start()
})
afterEach(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('shows an initial window', function () {
return this.app.client.getWindowCount().then(function (count) {
assert.equal(count, 1)
})
})
})
Spectron can work with any test framework. I prefer using mocha.
Clone this project for more info https://github.com/electron/spectron

Related

run vue3 ssr on cloudflare workers

I'm trying to run a vue ssr app on cloudflare workers.
I generated a new project using wrangler generate test
I installed vue using npm install vue#next and npm install #vue/server-renderer
I edited the index.js file like this:
const { createSSRApp } = require('vue')
const { renderToString } = require('#vue/server-renderer')
const app = createSSRApp({
data: () => ({ msg: 'hello' }),
template: `<div>{{ msg }}</div>`
})
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const html = await renderToString(app)
return new Response(html, {status: 200})
}
I then used wrangler dev to test it, but when I access the page I get this error:
ReferenceError: __VUE_PROD_DEVTOOLS__ is not defined
at Module.<anonymous> (worker.js:8:104768)
at n (worker.js:1:110)
at Object.<anonymous> (worker.js:8:104943)
at n (worker.js:1:110)
at worker.js:1:902
at worker.js:1:912
Any help or guidance is appreciated
I faced similar issue and was able to fix it by defining a global constant (VUE_PROD_DEVTOOLS = false) during compile time.
Here is how my webpack prod config looks like:
const webpack = require('webpack');
const { merge } = require("webpack-merge");
const webpackCommon = require("./webpack.common");
const prodConfig = {
mode: 'production',
plugins: [
new webpack.DefinePlugin({
__VUE_PROD_DEVTOOLS__: JSON.stringify(false)
}),
]
};
module.exports = merge(webpackCommon, prodConfig);

Using mocha and chai with import synax in VueJS

I'm trying to add Pact tests to my existing VueJS application but I'm having trouble even with the most basic test setup (using mocha with chai).
This is the basic test to see if things are working at all:
import { should } from "chai";
describe("setup", () => {
it("should work", () => {
var x = true;
x.should.be.equal(true);
});
});
Running this with the following command:
mocha --require #babel/preset-env test/pact/**/*.pact.js
This results in:
import { should } from "chai";
^
SyntaxError: Unexpected token {
From what I understood I need to transpile. After searching for similar issues I added this:
babel.config.js
module.exports = {
presets: ["#vue/app", "#babel/preset-env"]
};
Same effect.
It works when using e.g.
var should = require("chai").should();
describe("setup", () => {
it("should work", () => {
var x = true;
x.should.be.equal(true);
});
});

Spectron with mocha and chai does not work

I am trying to write a tests with Spectron for our Electron App, but I am running into problems with the setup. I use the classical setup with chai. I have one file which contains setup code:
const path = require("path");
const { Application } = require("spectron");
module.exports = {
initialiseSpectron: () => {
let electronPath = path.join(__dirname, "../../node_modules", ".bin", "electron");
if (process.platform == "win32") {
electronPath += ".cmd";
}
return new Application({
path: electronPath,
args: [path.join(__dirname, "../index.ts"), path.join(__dirname, "../../package.json")],
env: {
ELECTRON_ENABLE_LOGGING: true,
ELECTRON_ENABLE_STACK_DUMPING: true,
NODE_ENV: "development"
},
startTimeout: 10000,
chromeDriverLogPath: "../chromedriverlog.txt"
});
},
sleep: time => new Promise(resolve => setTimeout(resolve, time))
};
And then the test itself:
const chaiAsPromised = require("chai-as-promised");
const chai = require("chai");
chai.should();
chai.use(chaiAsPromised);
const testHelper = require("./initialise");
const app = testHelper.initialiseSpectron();
// Setup Promises and start Application
before(() => app.start());
// Tear down App after Tests are finished
after(() => {
if (app && app.isRunning()) {
return app.stop();
}
});
describe("Login", () => {
it("opens a window", function() {
return app.client
.waitUntilWindowLoaded()
.getWindowCount()
.should.eventually.equal(1);
});
it("tests the title", () =>
app.client
.waitUntilWindowLoaded()
.getTitle()
.should.eventually.equal("VIPFY"));
});
My problem is that I always get this error:
1) "before all" hook in "{root}"
0 passing (2s)
1 failing
1) "before all" hook in "{root}":
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
So it looks like the App does not start. But that is not true. The App Window opens, but it seems like the test does not recognize that. I have already tried changing the path using all kinds of syntax. But nothing worked. What am I missing?
Have you tried to increase the timeout for mocha?
Sometimes I had it fail first time, then worked on the second try.
See a working sample here with Electron 6:
https://github.com/florin05/electron-spectron-example

how to automate electron exe file using protractor framework

Please tell me in detail ..
I have an electron application and I have exe of that .. but want to automate using protractor framework.
Guide me in that .
You should try using Spectron
https://electronjs.org/spectron
Spectron is a testing tool for electron application. You can test it after packing into a exe file or straight away starting the test by mentioning the main.js
npm install --save-dev spectron
Install spectron via npm . Below example uses mocha for assertions.
To get up and running from your command line:
Install mocha locally as a dev dependency.
npm i mocha -D
create a spec file like below
const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron')
const path = require('path')
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
global.before(() => {
chai.should();
chai.use(chaiAsPromised);
});
describe('Application launch', function () {
this.timeout(10000)
beforeEach(function () {
const opts = {
path: './your.exe'
};
const app = new Application(opts);
return app.start().then((app) => {
chaiAsPromised.transferPromiseness = app.transferPromiseness;
return app;
})
})
afterEach(function () {
if (this.app && this.app.isRunning()) {
return this.app.stop()
}
})
it('shows an initial window', function () {
return this.app.client.getWindowCount().then(function (count) {
assert.equal(count, 1)
// Please note that getWindowCount() will return 2 if `dev tools` are opened.
// assert.equal(count, 2)
})
})
})
Run the test by:
mocha spec.js

How to test an Electron app with selenium webdriver

I have read the documentation and I have followed the tutorial step by step and I only have managed to run the app.
Documentation: http://electron.atom.io/docs/tutorial/using-selenium-and-webdriver/
The connection with chromedriver I cannot make it work, when I launch the test and try click a simple button I get this:
Error: ChromeDriver did not start within 5000ms at Error (native)
at node_modules/spectron/lib/chrome-driver.js:58:25 at
Request._callback (node_modules/spectron/lib/chrome-driver.js:116:45)
at Request.self.callback
(node_modules/spectron/node_modules/request/request.js:200:22) at
Request.
(node_modules/spectron/node_modules/request/request.js:1067:10) at
IncomingMessage.
(node_modules/spectron/node_modules/request/request.js:988:12) at
endReadableNT (_stream_readable.js:913:12) at _combinedTickCallback
(internal/process/next_tick.js:74:11) at process._tickCallback
(internal/process/next_tick.js:98:9)
My code:
"use strict";
require("co-mocha");
var Application = require('spectron').Application;
var assert = require('assert');
const webdriver = require('selenium-webdriver');
const driver = new webdriver.Builder()
.usingServer('http://127.0.0.1:9515')
.withCapabilities({
chromeOptions: {
binary: "./appPath/app"
}
})
.forBrowser('electron')
.build();
describe('Application launch', function () {
this.timeout(100000);
var app;
beforeEach(function () {
app = new Application({
path: "./appPath/app"
});
return app.start();
});
afterEach(function () {
if (app && app.isRunning()) {
return app.stop();
}
});
it('click a button', function* () {
yield driver.sleep(5000);
yield driver.findElement(webdriver.By.css(".classSelector")).click();
});
});
Thanks and sorry for my English.
I recommend you to use Spectron. which is a less painful way of testing your electron app. in my opinion perfect combination is using it with Ava test framework, which allows the concurrently test.
async & await is also another big win. which allows you to have so clean test cases.
and also if you have a test which needs to happen serial, you can use test.serial
test.serial('login as new user', async t => {
let app = t.context.app
app = await loginNewUser(app)
await util.screenshotCreateOrCompare(app, t, 'new-user-mission-view-empty')
})
test.serial('Can Navigate to Preference Page', async t => {
let app = t.context.app
await app.client.click('[data-test="preference-button"]')
await util.screenshotCreateOrCompare(app, t, 'new-user-preference-page-empty')
})
and just for reference; my helper test cases.
test.before(async t => {
app = util.createApp()
app = await util.waitForLoad(app, t)
})
test.beforeEach(async t => {
t.context.app = app
})
test.afterEach(async t => {
console.log('test complete')
})
// CleanUp
test.after.always(async t => {
// This runs after each test and other test hooks, even if they
failed
await app.client.localStorage('DELETE', 'user')
console.log('delete all files')
const clean = await exec('rm -rf /tmp/DesktopTest')
await clean.stdout.on('data', data => {
console.log(util.format('clean', data))
})
await app.client.close()
await app.stop()
})
util function,
// Returns a promise that resolves to a Spectron Application once the app has loaded.
// Takes a Ava test. Makes some basic assertions to verify that the app loaded correctly.
function createApp (t) {
return new Application({
path: path.join(__dirname, '..', 'node_modules', '.bin',
'electron' + (process.platform === 'win32' ? '.cmd' : '')),
// args: ['-r', path.join(__dirname, 'mocks.js'), path.join(__dirname, '..')],
env: {NODE_ENV: 'test'},
waitTimeout: 10e3
})
}
First off, Spectron (which is a wrapper for WebdriverIO) and WebdriverJS (which is part of Selenium-Webdriver) are two different frameworks, you only need to use one of them for your tests.
If you are using WebdriverJS, then you need to run ./node_modules/.bin/chromedriver in this step: http://electron.atom.io/docs/tutorial/using-selenium-and-webdriver/#start-chromedriver
I could get ChromeDriver working by adding a proxy exception in my terminal.
export {no_proxy,NO_PROXY}="127.0.0.1"