wait for modules are loaded - requirejs

I have following code:
define([],
function() {
var AppSettings = function(){};
AppSettings.prototype = {
init: function() {
var that = this;
//...
require(views,function(){
var counter = 0;
for(view in that.settings.initViews) {
that.initViews[view] = new arguments[counter++];
}
console.log("init");
});
},
run: function() {
console.log("run");
}
};
return AppSettings;
}
);
And when I load AppSettings module:
require(["app_settings"],
function(AppSettings) {
var settings = new AppSettings();
settings.init();
setting.run();
}
);
I get following output:
run
init
This is probably because I am loding modules async in init method - but how I can 'wait' for them to load? I mean how I can ensure that all async alls are done and then call run?

Related

Protractor test case freezes when run on bamboo

When I run my test on Visual studio my test runs successfully. But when I try to run it on bamboo my browser freezes and my test fails with the jasmine timeout exception.
Please find my protractor conf file :
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var reporters = require('jasmine-reporters');
var co = require('co');
// Example usage:
// protractor --env=local
// protractor --env=local --specs=test/road/road-missing.js
var reporter = new HtmlScreenshotReporter({
dest: 'target/screenshots',
filename: 'Test_Report.html',
fixedScreenshotName: true
});
var junitReporter = new reporters.JUnitXmlReporter({
savePath: 'target/screenshots',
consolidateAll: false
});
var customReporter = {
specStarted: function(result) {
console.log('\n---------------- Spec started: ' + result.fullName + ' ----------------');
}
}
var FUNCTION_CONFIG = {
beforeLaunch: function () {
return new Promise(function (resolve) {
reporter.beforeLaunch(resolve);
});
},
onPrepare: function () {
// cleanup of a failed test, generating an alert: "You have unsent changes."
// This will log the error:
// UnexpectedAlertOpenError: unexpected alert open: {Alert text : You have unsent changes.}
afterEach(co.wrap(function*() {
browser.ignoreSynchronization = true;
// force leaving page by open page about:blank
yield browser.get("about:blank");
try {
// if no alert is shown an exception is thrown. This is the case if a test finished successful
var alert = yield browser.switchTo().alert();
yield alert.accept();
} catch (e) {
// case: no alert was shown. accessing alert will trhow an exception, which can be ignored
}
}));
browser.manage().window().setSize(480, 900);
jasmine.getEnv().addReporter(reporter);
var jasmineReporters = require('jasmine-reporters');
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'target/screenshots',
filePrefix: 'xmloutput'
}));
jasmine.getEnv().addReporter(customReporter);
},
afterLaunch: function (exitCode) {
return new Promise(function (resolve) {
reporter.afterLaunch(resolve.bind(this, exitCode));
});
}
};
function extend(obj, source) {
if (source) {
for (var prop in source) {
if (typeof obj[prop] === "object" && !Array.isArray(obj[prop]))
extend(obj[prop], source[prop]);
else
obj[prop] = source[prop];
}
}
return obj;
};
function getArgv(parameter) {
var argv = process.argv;
var param = parameter + "=";
for (var i = 0; i < argv.length; i++) {
if (argv[i].startsWith(parameter))
return argv[i].substring(param.length);
}
return undefined;
}
var DEFAULT_CONFIG = require('./env/default.js');
var env = getArgv('--env') || 'local';
var ENV_CONFIG = require('./env/' + env + '.js');
var conf = extend(FUNCTION_CONFIG, DEFAULT_CONFIG);
exports.config = extend(
conf,
ENV_CONFIG
);
Also this is one of the test case which fails on browser :
var UI = require('./../ui.js');
var co = require('co');
var ui = new UI();
describe("MapFeedback: address-infowrong", function () {
ui.setSmallScreenSize();
// ui.testLogger(100);
it("test", co.wrap(function* () {
yield browser.get(ui.createAddressStartLink());
yield ui.ADDRESS_PROBLEM.click();
var version = yield browser.executeScript('return mapfeedbackVersion');
console.log("Map feedback Version:" + version);
expect(browser.getCurrentUrl()).toContain("report_address");
yield ui.ADDRESS_INFO_WRONG.click();
expect(browser.getCurrentUrl()).toContain("select_address_edit/address_edit");
yield ui.zoomIn(18.5);
var elmOK = element(By.css('button[ng-click="doneSelectObject(selectedObject)"]'));
yield ui.waitFor(protractor.ExpectedConditions.elementToBeClickable(elmOK));
yield elmOK.click();
expect(browser.getCurrentUrl()).toContain("address_edit");
yield element(by.xpath("/html/body/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/input")).click();
yield element(by.xpath("//*[#id=\"input_addressNumber\"]")).sendKeys("TEST");
yield element(by.xpath(" /html/body/div[1]/div/div/div[2]/div[2]/div[4]/div[1]/input")).click();
yield element(by.xpath("//*[#id=\"input_address_other\"]")).sendKeys("TEST");
yield ui.SUBMIT.click();
expect(browser.getCurrentUrl()).toContain("submit");
yield ui.waitSubmit();
var reportId = yield browser.executeScript('return mapFeedBack.reportId');
console.log("address-infowrong id: " + reportId);
expect(yield element(By.css('div[ng-show="mapFeedBack.submitState==\'success\'"]')).isDisplayed()).toBeTruthy();
var req = yield ui.getMapFeedbackData(-reportId);
var body = JSON.parse(req.body);
console.log(body);
expect(body.properties.error).toEqual(21);
expect(body.properties.details).toEqual("Other address issue: TEST");
}));
});
Note : I am using a selenium grid for my test automation.
// --- config: default
module.exports = {
params: {
baseUrl: "NOT-SET",
urlParams: "zoomLevel=15",
urlParamCoords: "55.67653,12.56040", // Copanhagen Location
urlAddressParamCoords: "40.75170,-73.99420", //New York Location,
rest: {
baseUrl: "NOT-SET",
header: {
// 'Content-Type': 'application/vnd.here.layerObjectList+json; charset=UTF-8',
'Auth-Identifier': 'Y-7Wnc2lNk3fMI0n3-rZ',
'Auth-Secret': 'mEv_DZ1JKDDYzESUAp9KyQ',
'Auth-Service-Id': 'here_app',
'User-Agent': 'mapfeedback-test',
'Accept': 'application/vnd.here.layerObject+json',
'Group-Id': 'FGx1AWaAzKOo0imNkLmf'
}
}
},
seleniumAddress: "http://selenium.community.nw.ops.here.com:4444/wd/hub",
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
maxInstances: 1
},
// Framework to use. Jasmine is recommended.
framework: 'jasmine',
// Spec patterns are relative to the current working directly when protractor is called.
specs: [
// Note: group & sort tests by feature
'./test/address/address-remove.js',
'./test/address/address-missing.js',
'./test/address/address-infowrong.js',
'./test/border/border-linemissing.js',
'./test/border/border-linedrawnwrong.js',
'./test/other/other-cartoincorrect.js',
'./test/other/other-cartomissing.js',
'./test/other/other-cartoremove.js',
'./test/place/place-closed.js',
'./test/place/place-offensivecontent.js',
'./test/place/place-violateprivacy.js',
'./test/place/place-Inappropriatebehaviour.js',
'./test/place/place-otherviolation.js',
'./test/place/place-copyright.js',
'./test/place/place-otherissue.js',
'./test/place/place-missing.js',
'./test/place/place-infowrong.js',
'./test/road/road-missing.js',
'./test/road/road-closed.js',
'./test/road/road-infowrong.js',
'./test/satellite/satellite-conflictimage.js',
'./test/satellite/satellite-obscuredimage.js',
'./test/satellite/satellite-oldimage.js',
'./test/satellite/satellite-unclearimage.js',
],
// Options to be passed to Jasmine.
jasmineNodeOpts: {
defaultTimeoutInterval: 50000
}
};
Please help ??

Using Babel to Get ApolloClient to ES5 CommonJS Module Format for Node Environment

Using Babel to Get ApolloClient to ES5 CommonJS Module Format
Im trying to use Babel to get the apollo-client module to work as ES5 in a non-browser, node environment. I've gone through step below which always give me the same result. Im trying to figure out if that result is right result for a node environment. When I import the babel processed documents into my project and call a method that should be exported, im getting, cannot find module. For context, the project is a fusetools.com demo. Fusetools does not support ES2015 Promises so the idea is that with the babel es2015 preset, it should work. I'm mostly chasing this down to learn something but it would be great if I could get it to work. Any comments on an easier way to do this, now that I understand it better, would be greatly appreciated. The project where I babeled the code can be found here. The fusetools project where i used the transformed code is here.
The error I get is :
LOG: Error: JavaScript error in MainView.ux line 9: Name: Fuse.Scripting.Error
Error message: require(): module not found: js/apollo-client/ApolloClient.js
File name: MainView.ux
Line number: 9
Source line: var ApolloClient = require('js/apollo-client/ApolloClient.js');
This is the code im trying to reach:
```
"use strict";
var networkInterface_1 = require('./transport/networkInterface');
var isUndefined = require('lodash.isundefined');
var assign = require('lodash.assign');
var isString = require('lodash.isstring');
var store_1 = require('./store');
var QueryManager_1 = require('./core/QueryManager');
var storeUtils_1 = require('./data/storeUtils');
var fragments_1 = require('./fragments');
var getFromAST_1 = require('./queries/getFromAST');
var DEFAULT_REDUX_ROOT_KEY = 'apollo';
function defaultReduxRootSelector(state) {
return state[DEFAULT_REDUX_ROOT_KEY];
}
var ApolloClient = function () {
function ApolloClient(_a) {
var _this = this;
var _b = _a === void 0 ? {} : _a,
networkInterface = _b.networkInterface,
reduxRootKey = _b.reduxRootKey,
reduxRootSelector = _b.reduxRootSelector,
initialState = _b.initialState,
dataIdFromObject = _b.dataIdFromObject,
resultTransformer = _b.resultTransformer,
resultComparator = _b.resultComparator,
_c = _b.ssrMode,
ssrMode = _c === void 0 ? false : _c,
_d = _b.ssrForceFetchDelay,
ssrForceFetchDelay = _d === void 0 ? 0 : _d,
_e = _b.mutationBehaviorReducers,
mutationBehaviorReducers = _e === void 0 ? {} : _e,
_f = _b.addTypename,
addTypename = _f === void 0 ? true : _f,
queryTransformer = _b.queryTransformer;
this.middleware = function () {
return function (store) {
_this.setStore(store);
return function (next) {
return function (action) {
var returnValue = next(action);
_this.queryManager.broadcastNewStore(store.getState());
return returnValue;
};
};
};
};
if (reduxRootKey && reduxRootSelector) {
throw new Error('Both "reduxRootKey" and "reduxRootSelector" are configured, but only one of two is allowed.');
}
if (reduxRootKey) {
console.warn('"reduxRootKey" option is deprecated and might be removed in the upcoming versions, ' + 'please use the "reduxRootSelector" instead.');
this.reduxRootKey = reduxRootKey;
}
if (queryTransformer) {
throw new Error('queryTransformer option no longer supported in Apollo Client 0.5. ' + 'Instead, there is a new "addTypename" option, which is on by default.');
}
if (!reduxRootSelector && reduxRootKey) {
this.reduxRootSelector = function (state) {
return state[reduxRootKey];
};
} else if (isString(reduxRootSelector)) {
this.reduxRootKey = reduxRootSelector;
this.reduxRootSelector = function (state) {
return state[reduxRootSelector];
};
} else if (typeof reduxRootSelector === 'function') {
this.reduxRootSelector = reduxRootSelector;
} else {
this.reduxRootSelector = null;
}
this.initialState = initialState ? initialState : {};
this.networkInterface = networkInterface ? networkInterface : networkInterface_1.createNetworkInterface({ uri: '/graphql' });
this.addTypename = addTypename;
this.resultTransformer = resultTransformer;
this.resultComparator = resultComparator;
this.shouldForceFetch = !(ssrMode || ssrForceFetchDelay > 0);
this.dataId = dataIdFromObject;
this.fieldWithArgs = storeUtils_1.storeKeyNameFromFieldNameAndArgs;
if (ssrForceFetchDelay) {
setTimeout(function () {
return _this.shouldForceFetch = true;
}, ssrForceFetchDelay);
}
this.reducerConfig = {
dataIdFromObject: dataIdFromObject,
mutationBehaviorReducers: mutationBehaviorReducers
};
this.watchQuery = this.watchQuery.bind(this);
this.query = this.query.bind(this);
this.mutate = this.mutate.bind(this);
this.setStore = this.setStore.bind(this);
this.resetStore = this.resetStore.bind(this);
}
ApolloClient.prototype.watchQuery = function (options) {
this.initStore();
if (!this.shouldForceFetch && options.forceFetch) {
options = assign({}, options, {
forceFetch: false
});
}
fragments_1.createFragment(options.query);
var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
var realOptions = Object.assign({}, options, {
query: fullDocument
});
delete realOptions.fragments;
return this.queryManager.watchQuery(realOptions);
};
;
ApolloClient.prototype.query = function (options) {
this.initStore();
if (!this.shouldForceFetch && options.forceFetch) {
options = assign({}, options, {
forceFetch: false
});
}
fragments_1.createFragment(options.query);
var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
var realOptions = Object.assign({}, options, {
query: fullDocument
});
delete realOptions.fragments;
return this.queryManager.query(realOptions);
};
;
ApolloClient.prototype.mutate = function (options) {
this.initStore();
var fullDocument = getFromAST_1.addFragmentsToDocument(options.mutation, options.fragments);
var realOptions = Object.assign({}, options, {
mutation: fullDocument
});
delete realOptions.fragments;
return this.queryManager.mutate(realOptions);
};
;
ApolloClient.prototype.subscribe = function (options) {
this.initStore();
var fullDocument = getFromAST_1.addFragmentsToDocument(options.query, options.fragments);
var realOptions = Object.assign({}, options, {
document: fullDocument
});
delete realOptions.fragments;
delete realOptions.query;
return this.queryManager.startGraphQLSubscription(realOptions);
};
ApolloClient.prototype.reducer = function () {
return store_1.createApolloReducer(this.reducerConfig);
};
ApolloClient.prototype.initStore = function () {
if (this.store) {
return;
}
if (this.reduxRootSelector) {
throw new Error('Cannot initialize the store because "reduxRootSelector" or "reduxRootKey" is provided. ' + 'They should only be used when the store is created outside of the client. ' + 'This may lead to unexpected results when querying the store internally. ' + "Please remove that option from ApolloClient constructor.");
}
this.setStore(store_1.createApolloStore({
reduxRootKey: DEFAULT_REDUX_ROOT_KEY,
initialState: this.initialState,
config: this.reducerConfig
}));
this.reduxRootKey = DEFAULT_REDUX_ROOT_KEY;
};
;
ApolloClient.prototype.resetStore = function () {
this.queryManager.resetStore();
};
;
ApolloClient.prototype.setStore = function (store) {
var reduxRootSelector;
if (this.reduxRootSelector) {
reduxRootSelector = this.reduxRootSelector;
} else {
reduxRootSelector = defaultReduxRootSelector;
this.reduxRootKey = DEFAULT_REDUX_ROOT_KEY;
}
if (isUndefined(reduxRootSelector(store.getState()))) {
throw new Error('Existing store does not use apolloReducer. Please make sure the store ' + 'is properly configured and "reduxRootSelector" is correctly specified.');
}
this.store = store;
this.queryManager = new QueryManager_1.QueryManager({
networkInterface: this.networkInterface,
reduxRootSelector: reduxRootSelector,
store: store,
addTypename: this.addTypename,
resultTransformer: this.resultTransformer,
resultComparator: this.resultComparator,
reducerConfig: this.reducerConfig
});
};
;
return ApolloClient;
}();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ApolloClient;
//# sourceMappingURL=ApolloClient.js.map
```
Any and all comments I might learn from are appreciated. Thank you.
One way to do this would be to use webpack like this:
const webpack = require('webpack');
const path = require('path');
module.exports = {
// watch: true,
entry: {
ApolloClient: './config/ApolloClient.js',
createNetworkInterface: './config/createNetworkInterface.js',
Redux: './config/Redux.js',
},
output: {
path: path.join(__dirname, 'build/Libs'),
filename: '[name].js',
library: '[name]',
libraryTarget: 'commonjs',
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
Then in config directory you could have:
/* ApolloClient.js */
import { ApolloClient } from 'apollo-client';
export default ApolloClient;
and
/* createNetworkInterface.js */
import { createNetworkInterface } from 'apollo-client/transport/networkInterface';
export default createNetworkInterface;
plus if you want to have Redux as well:
/* Redux.js */
import * as Redux from 'redux';
export default Redux;
However I was not able to get gql done this way and had to use bolav's fusepm.
Which you would use exactly as bolav has mention, first install it globally:
npm install -G fusepm and then fusepm npm graphql-tag
Once you have all these in place you can require them as follow:
var Redux = require('build/Libs/Redux');
var ApolloClient = require('build/Libs/ApolloClient');
var createNetworkInterface = require('build/Libs/createNetworkInterface');
var gql = require('fusejs_lib/graphql-tag_graphql-tag.umd');
This way still could use some TLC but for now, it works and get's the job done:
var networkInterface = createNetworkInterface.createNetworkInterface({
uri: 'http://localhost:8000/graphql',
});
var client = new ApolloClient.ApolloClient({
networkInterface,
});
client.query({
query: gql`
query {
allPosts {
edges {
node {
id
headline
summary(length: 80)
body
createdAt
updatedAt
personByAuthorId {
firstName
lastName
}
}
}
}
}
`,
})
.then(data => data.data.allPosts.edges.forEach(node => pages.add(createPage(node))))
.catch(error => console.log(error));
Also if you like I've setup a whole project along with server that might be of an interest to you: fuseR
I made fusepm, which has a mode to convert npm modules to run them under FuseTools. It's still has a lot of bugs, but at least I managed to come longer than you:
fuse create app apolloc
cd apolloc
npm install apollo-client
fusepm npm apollo-client
And then in your javascript:
<JavaScript>
var ApolloClient = require('fusejs_lib/apollo-client.js');
</JavaScript>
fusepm uses Babel, with some custom plugins.

Initialize a module when it's required

I have a module with some initialization code inside. The init should be performed when the module is loaded. At the moment I'm doing it like this:
// in the module
exports.init = function(config) { do it }
// in main
var mod = require('myModule');
mod.init(myConfig)
That works, but I'd like to be more concise:
var mod = require('myModule').init('myConfig')
What should init return in order to keep mod reference working?
You can return this, which is a reference to exports in this case.
exports.init = function(init) {
console.log(init);
return this;
};
exports.myMethod = function() {
console.log('Has access to this');
}
var mod = require('./module.js').init('test'); //Prints 'test'
mod.myMethod(); //Will print 'Has access to this.'
Or you could use a constructor:
module.exports = function(config) {
this.config = config;
this.myMethod = function() {
console.log('Has access to this');
};
return this;
};
var myModule = require('./module.js')(config);
myModule.myMethod(); //Prints 'Has access to this'

WinJS System.Launcher only working in debug mode

The following code works flawlessly when run in debug mode (F5) .. but when deployed (as a app tile) or run without the debugger (ctl+f5), it does not work properly.
behaviour expected/ when working: clicking the tile launches the steam url link immediately, without rendering the html page visibly.
behaviour received/ not working: clicking the tile launches the app, only rendering the html page and never launches the steam url.
var mydefs = new Object();
mydefs = { url: 'steam://rungameid/200710' };
function launch(url) {
var uri = new Windows.Foundation.Uri(url);
Windows.System.Launcher.launchUriAsync(uri).then(
function (success) {
if (success) {
// File launched
window.close();
} else {
// File launch failed
}
});
}
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
launch(mydefs.url);
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
window.close();
};
app.start();
})();
Looks like a timing issue. The following works for me as a tile
(function () {
"use strict";
var mydefs = new Object();
mydefs = { url: 'steam://rungameid/200710' };
WinJS.Namespace.define("Steam", {
launch: function launch(url) {
var uri = new Windows.Foundation.Uri(url);
Windows.System.Launcher.launchUriAsync(uri).then(
function (success) {
if (success) {
// File launched
window.close();
} else {
// File launch failed
}
});
}
});
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
setTimeout('Steam.launch("steam://rungameid/200710");', 2000);
args.setPromise(WinJS.UI.processAll());
}
};
app.start();
})();

How to spy on a property that is not exported

I have a module "sitescollection" like this:
var site = require('./site'); // <- this should be stubbed
var sitesCollection = function(spec) {
var that = {};
that.sites = {};
that.findOrCreateById = function(id) {
if (typeof(that.sites[id]) == "undefined") {
that.sites[id] = site({id: id}); // <- its used here
}
return that.sites[id];
};
return that;
};
module.exports = sitesCollection;
so within sitescollection, site is a module that is not exported. But inside the code, i use it. Now i'm writing jasmine specs for #findOrCreateById().
I want to spec my the findOrCreateBy() function. But i want to stub the site() function, because the spec should be independent from the implementation. Where do i have to create the spyed method on?
var sitescollection = require('../../lib/sitescollection');
describe("#findOrCreateById", function() {
it("should return the site", function() {
var sites = sitescollection();
mysite = { id: "bla" };
// Here i want to stub the site() method inside the sitescollection module.
// spyOn(???,"site").andRetur(mysite);
expect(sites.findOrCreateById(mysite.id)).toEqual(mysite);
});
});
You can achieve this using https: //github.com/thlorenz/proxyquire
var proxyquire = require('proxyquire');
describe("#findOrCreateById", function() {
it("should return the site", function() {
// the path '../../lib/sitescollection' is relative to this test file
var sitesCollection = proxyquire('../../lib/sitescollection', {
// the path './site' is relative to sitescollection, it basically
// should be an exact match for the path passed to require in the
// file you want to test
'./site': function() {
console.log('fake version of "./site" is called');
}
});
// now call your sitesCollection, which is using your fake './site'
var sites = sitesCollection();
var mysite = {
id: "bla"
};
expect(sites.findOrCreateById(mysite.id)).toEqual(mysite);
});
});

Resources