Nightwatch: Separate xpath into another files - testing

How to separate xpath into separate file and use it in nightwatch automation testing?
EDIT:
I running a page object pattern example and found some errors.
Errors: TypeError: browser.page.url is not a function
Please help on this.
module.exports = {
url: 'http://localhost:63916/Login/Login',
elements: {
username: {
selector: '//*[#id="inputName"]',
locateStrategy: 'xpath'
}
}
};
module.exports = (function(settings) {
settings.test_workers = false;
return settings;
})(require('./nightwatch.json'));
//const data = require('./data.js')
module.exports = {
'Login' : function (browser) {
var page = browser.page.url();
page.navigate()
.setValue('#username', 'peter')
browser.end()
}
};

So assuming the page object is defined in pages directory. You need to change your nightwatch.conf.js like below
nightwatch.conf.js
module.exports = (function(settings) {
settings.test_workers = false;
settings.page_objects_path = "./pages";
return settings;
})(require('./nightwatch.json'));
Your pages has a file named main.js
pages/main.js
module.exports = {
url: 'https://gmail.com',
elements: {
username: {
selector: '//*[#id="identifierId"]',
locateStrategy: 'xpath'
},
next: {
selector: '#identifierNext span',
locateStrategy: 'css'
}
}
};
And then you test is like below
tests/test.main.js
module.exports = {
'Login' : function (browser) {
var page = browser.page.main();
page.navigate()
.setValue('#username', 'peterlalwani')
.click('#next')
.waitForElementNotPresent("#username", 10000);
browser.saveScreenshot("./so.png")
browser.end()
}
};
Now when you run it, it creates a so.png
I created a sample repo for you to clone and see the above
https://github.com/tarunlalwani/nightwatch-page-object-so.git
PS: It is important to note that var page = browser.page.main(); means it would load main.js from the pages folder here.

Related

How to dynamically access a remote component in vue js with module federation

I am trying to build a vue js 2 microfrontend with module federation. I dont want to use static remote imports via the webpack.config.js like this
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
app1: 'app1#http://localhost:3001/remoteEntry.js',
},
}),
],
};
I am looking for a way to dynamically import vue components into my host application. I tried this approach so far, but i only found examples that worked with angular or react.
The goal is to have multiple remote frontends that can automatically register somewhere, maybe in some kind of store. The host application then can access this store and get all of the registered remote applications (name, url, components). The host application then loads the components and should be able to use them. I remote import the component HelloDerp, the loading process is working fine but i dont know how to render it on my host application. I read the vue js doc about dynamic and async imports but i think that only works for local components.
What i've got so far in the host application:
<template>
<div id="app">
<HelloWorld />
<HelloDerp />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
const HelloDerp = null;
export default {
name: "App",
components: {
HelloWorld,
HelloDerp,
},
mounted() {
var remoteUrlWithVersion = "http://localhost:9000/remoteEntry.js";
const element = document.createElement("script");
element.type = "text/javascript";
element.async = true;
element.src = remoteUrlWithVersion;
element.onload = () => {
console.log(`Dynamic Script Loaded: ${element.src}`);
HelloDerp = loadComponent("core", "./HelloDerp");
};
document.head.appendChild(element);
return null;
},
};
async function loadComponent(scope, module) {
// Initializes the shared scope. Fills it with known provided modules from this build and all remotes
await __webpack_init_sharing__("default");
const container = window[scope]; // or get the container somewhere else
// Initialize the container, it may provide shared modules
await container.init(__webpack_share_scopes__.default);
const factory = await window[scope].get(module);
const Module = factory();
return Module;
}
</script>
Sorry i almost forgot about this. Here's my solution.
Load Modules:
export default async function loadModules(
host: string,
ownModuleName: string,
wantedNames: string[]
): Promise<RemoteComponent[]> {
...
uiApplications.forEach((uiApplication) => {
const remoteURL = `${uiApplication.protocol}://${uiApplication.host}:${uiApplication.port}/${uiApplication.moduleName}/${uiApplication.fileName}`;
const { componentNames } = uiApplication;
const { moduleName } = uiApplication;
const element = document.createElement('script');
element.type = 'text/javascript';
element.async = true;
element.src = remoteURL;
element.onload = () => {
componentNames?.forEach((componentName) => {
const component = loadModule(moduleName, `./${componentName}`);
component.then((result) => {
if (componentName.toLowerCase().endsWith('view')) {
// share views
components.push(new RemoteComponent(result.default, componentName));
} else {
// share business logic
components.push(new RemoteComponent(result, componentName));
}
});
});
};
document.head.appendChild(element);
});
});
...
}
export default async function loadModule(scope: string, module: string): Promise<any> {
await __webpack_init_sharing__('default');
const container = window[scope]; // or get the container somewhere else
await container.init(__webpack_share_scopes__.default);
const factory = await window[scope].get(module);
const Module = factory();
return Module;
}
Add Modules to routes
router.addRoute({
name: remoteComponent.componentName,
path: `/${remoteComponent.componentName}`,
component: remoteComponent.component,
});

how to use rollup to parse cucumber feature files and backing step definition files

I have the following rollup plugin that will include .feature files
export const cucumberRollupPlugin: PluginImpl<CucumberOptions> = pluginOptions => {
let options: CucumberOptions = {
...{
include: '**/*.feature',
cwd: process.cwd(),
},
...pluginOptions,
};
let filter = createFilter(options);
let plugin: Plugin = {
name: 'bigtest-cucumber',
async transform(code, id) {
if (!filter(id)) {
return;
}
let parser = new GherkinParser({ code, uri: id, rootDir: options.cwd });
let result = await parser.parse();
let esm = dataToEsm(result, { namedExports: false });
// TODO: add sourcemap support
let transformResult: TransformResult = { code: esm };
return transformResult;
},
};
return plugin;
};
The problem I have is that to make the feature files work, there are step definition files that actually contain the functionality. So a feature file might look like this
Feature: Visit career guide page in career.guru99.com
Scenario: Visit career.guru99.com
Given: I browse to career.guru99.com
And a step definition file might look like this:
import { Given, When, Then from 'cucumber';
import assert from 'assert';
import{ driver } from '../support/web_driver';
Given(/^browse to web site "([^"]*)"$/, async function(url) {
return driver.get(url);
});
The problem I have with rollup is that there are no import statements for either the step definition files. The way cucumber-js works is that these files are found at runtime.
I think I need to generate an index.js that looks like this to cover the step definitions.
import from './step_definition_1';
import from './step_definition_2';
import from './step_definition_3';
Where would this fit in the rollup pipeline to generate this file so it can get pulled into the rollup pipeline.
You can use this.emitFile to manually process the .feature files and include them in the output. Call this.emitFile for each .feature file in the buildStart hook (each emitted file will get processed through the transform hook you wrote).
Here's an example that uses the globby package (which expands a glob to an array of file paths) to get the file path of each .feature file to pass to this.emitFile:
import globby from 'globby'
export const cucumberRollupPlugin: PluginImpl<CucumberOptions> = pluginOptions => {
let options: CucumberOptions = {
include: '**/*.feature',
cwd: process.cwd(),
...pluginOptions,
};
let filter = createFilter(options);
let plugin: Plugin = {
name: 'bigtest-cucumber',
async buildStart({ include, cwd }) {
const featureFilePaths = await globby(include, { cwd });
for (const featureFilePath of featureFilePaths) {
this.emitFile({
type: 'chunk',
id: featureFilePath
});
}
},
async transform(code, id) {
if (!filter(id)) {
return;
}
let parser = new GherkinParser({ code, uri: id, rootDir: options.cwd });
let result = await parser.parse();
let esm = dataToEsm(result, { namedExports: false });
// TODO: add sourcemap support
let transformResult: TransformResult = { code: esm };
return transformResult;
},
};
return plugin;
};
Let me know if you have any questions!
You need to use the this.emitFile method and befor that lookup the files via glob or anything else inside your plugin
{
plugins: [typescript(),{
name: "emit-additional-files",
async transform(code,id) {
//id === fileName
//code === fileContent
// inspect code or id here then use path.resolve() and fs.readdir to find additional files
this.emitFile()
}
}]
}

Ant Design Pro dynamic menu not showing up

Following the instruction at https://pro.ant.design/docs/router-and-nav#fetch-menu-from-server
I changed file BasicLayout.tsx as below. Menu is not showing up.
...
const testMenu = [{name:"login", path:"/user/login"}] as any;
const [menuData, setMenuData] = useState([]);
useEffect(() => {
if (dispatch) {
dispatch({
type: 'user/fetchCurrent',
});
}
setMenuData(testMenu)
}, []);
...
menuDataRender={()=>menuData}
...
I was doing same as you and failed as you. Document is still wrong.
And I found getting menu from server has a lot of bug with ant design pro v4. (Maybe I did not know)
So my final decision is to display all menu from /config/config.ts as designed initially.
And get only authorization information from server and set only authority to show only logged in user related menu.
So my solution (not correct answer) is:
I referenced this link. https://umijs.org/docs/runtime-config#patchroutes-routes-
Created file /src/app.tsx and inserted code as follow:
interface PathAndIdsModel {
path: string;
ids: string[];
}
const setAuthority = (routes: any, pathAndIds: PathAndIdsModel[]) => {
routes.forEach((route: any) => {
const found = pathAndIds.find((item) => item.path === route.path);
if (found) {
// eslint-disable-next-line no-param-reassign
route.authority = [...new Set([...(route.authority || []), ...found.ids])];
}
if (route.routes) {
setAuthority(route.routes, pathAndIds);
}
});
};
async function patchRoutes({ routes }) {
const response = await fetch(`https://localhost:44357/authorities`);
const pathAndIds = await response.json();
setAuthority(routes, pathAndIds);
}
export { patchRoutes };
Inserted following code to ASP.Net Core Controller:
[HttpGet("/authorities")]
public IEnumerable<object> Authorities()
{
return new[]
{
new {
Path = "/dashboard/analysis",
Ids = new [] { "user", "admin", },
},
new {
Path = "/dashboard/monitor",
Ids = new [] { "user", "admin", },
},
new {
Path = "/dashboard/workplace",
Ids = new [] { "admin", },
},
new {
Path = "/form/basic-form",
Ids = new [] { "admin", },
},
};
}
/dashboard/workplace and /form/basic-form page will be hidden if logged in as user, but shows if logged in as admin.
I tried to get full routes from server, but failed because of async call, UmiJS did not wait until fetching from server and setting new routes.
So when I fetched routes from server and changed routes, UmiJS already converted icon and component of old routes and my new routes never changed.

Fail to mock with Intern more than once

I have followed the guide from Sitepen to mock AMD modules (LINK), but when I try to mock the same Module twice, the mocking fails, telling me my mock has no constructor. It crashes in the AMD-Mocker here:
try {
originalModule = require(moduleId); [...]
}
Has anybody ever stumbled across this issue and has found a solution for it? It does not help to create two test files, either.
Here is my compressed code:
define(function (require) {
var registerSuite = require('intern!object');
var assert = require('intern/chai!assert');
var amdMocker = require('support/AMDMocker');
registerSuite( function(){
var Hello;
return{
before: function(){
return amdMocker.mock('amd/Hello', {
'amd/Resolver': 'support/ResolverMocked'
}).then(function (mocked) {
Hello = mocked;
});
},
name: 'helloMocked',
'greet': function () {
var hello = new Hello();
}
}
});
registerSuite( function(){
var Hello2;
return{
before: function(){
return amdMocker.mock('amd/Hello', {
'amd/Resolver': 'support/ResolverMocked'
}).then(function (mocked) {
Hello2 = mocked;
});
},
name: 'helloMocked2',
'greet': function () {
var hello = new Hello2(); // here it crashes
}
}
});
});

How to structure multiple pages with RequireJS

How to structure multiple pages with RequireJS? Is, like the following sample, declaring every class in app.js is the right thing to do? Has every html file to declare the <script data-main="src/main" src="src/require.js"></script>?
What I want to avoid is loading all the script when a user reach the first page of a site.
main.js defining all external dependencies:
require(
{
baseUrl:'/src'
},
[
"require",
"order!http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
"order!http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js",
"order!http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js",
"order!http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"
],
function (require) {
require(["app"], function (app) {
app.start();
});
}
);
app.js file defining every component:
define([ "product/ProductSearchView",
"product/ProductCollection"
], function (ProductSearchView,
ProductCollection) {
return {
start: function() {
var products = new ProductCollection();
var searchView = new ProductSearchView({ collection: products });
products.fetch();
return {};
}
}
});
You can require files within your existing module. So say when someone clicks a link you could trigger a function that does the following:
// If you have a require in your other module
// The other module will execute its own logic
require(["module/one"], function(One) {
$("a").click(function() {
require(["new/module"]);
});
});
// If you have a define in your other module
// You will need to add the variable to the require
// so you can access its methods and properties
require(["module/one"], function(One) {
$("a").click(function() {
require(["new/module"], function(NewModule) {
NewModule.doSomething();
});
});
});
This is a complete example of how this all works; require.js and order.js are in the same directory as the app's JS files.
<html>
<head>
<script data-main="js/test" src="js/require.js"></script>
</head>
<body>
<button>Clickme</button>
</body>
</html>
test.js (in js folder)
require(
{
baseUrl:'/js'
},
[
"order!//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js",
"order!//ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"
],
function () {
require(["app"], function (app) {
app.start();
});
}
);
app.js (in js folder) with a on-demand load of Employee.js:
define([], function () {
return {
start: function() {
$('button').button();
$('button').click(function() {
require(['Employee'], function(Employee) {
var john = new Employee('John', 'Smith');
console.log(john);
john.wep();
});
});
return {};
}
}
});
Employee.js (in js folder):
define('Employee', function () {
return function Employee(first, last) {
this.first = first;
this.last = last;
this.wep = function() {
console.log('wee');
}
};
});