velocity is not a function - requirejs

I am using requirejs to load my file(s) and dependancies.
I am then using grunt to compress everything into one file. I can see that all of my plugins are getting loaded/compiled in my final js file (above all of my application specific methods).
I have a select input with some values, when the select changes - depending on the value, I want to show/hide some additional things on my page. Pretty straight-forward.
What I don't quite understand is why i'm getting "velocity is not a function" when I call it. I know it's because it isn't seeing something - but what I can tell, everything is there.
Here is my config file and the application file that has the event listener.
Everything is working great - until velocity is called. Looking at the docs, it seems like I'm calling velocity correctly.
config.js
'use strict';
/**
* RequireJS configuration.
*
*/
requirejs.config({
'baseUrl': '/resources/js/',
'paths': {
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min',
'bootstrap': 'vendor/bootstrap.min',
'domReady': 'plugins/domReady',
'velocity': 'plugins/velocity.min'
},
'shim': {
'bootstrap': {
'deps': ['jquery']
}, 'velocity': {
'deps': ['jquery']
}
}
});
/**
* Application initialization.
*
* #param {object} application | Main application module.
* #returns {object}
*
*/
requirejs(['application'], function (application) {
application.initialize();
});
application.js
'use strict';
/**
* Primary application module.
*
* #param {function} $ | jQuery library.
* #returns {object}
*
*/
define([
'jquery',
'bootstrap',
'velocity',
'domReady!'
], function ($) {
var initialize = function () {
console.info('Application initialized');
/**
* Event listener for change.
*
* #param {object} event | The change event.
* #returns void
*
*/
$('#mySelect').change(function (event) {
switch ($(this).val()) {
case'Value One':
$('#isValueOne').velocity('slideDown', { 'duration': 1500 });
break;
case'Small Value Two':
break;
case'Value Three':
break;
default:
break;
}
});
};
return {
'initialize': initialize
};
});
html
<div id="isValueOne">
<h1>Hello World!</h1>
</div>
EDIT
If I use slideDown(), Everything works - the div slides down to reveal the text.
jquery
....
$("#isValueOne").slideDown("fast", function () {
// this works great.
});
EDIT
Here is my Gruntfile.js configuration:
grunt.initConfig({
'pkg': grunt.file.readJSON('package.json'),
'requirejs': {
'options': {
'baseUrl': 'resources/js',
'mainConfigFile': 'resources/js/config.js',
'name': 'application',
'include': ['config'],
'wrapShim': true,
'out': 'resources/js/application.js'
},
'development': {
'options': {
'_build': false,
'optimize': 'none',
'out': '../web/resources/js/application.js'
}
},
'production': {
'options': {
'_build': true,
'optimize': 'uglify',
'out': '../web/resources/js/application.min.js'
}
}
},
....
....
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.registerTask('development', ['requirejs:development', 'sass', 'watch']);
To run, I use grunt development

Related

TypeError: intlProvider.getChildContext is not a function

I'm using injectIntl in my react functional component to achieve the localization.
I'm using enzyme/jest to do the unit test. I've copied the intl-test-helper file, but got error:
" TypeError: intlProvider.getChildContext is not a function "
I've tried other suggestions from stackflow:
1. remove mock file --- which I don't have mock file
2. use const { IntlProvider } = jest.requireActual("react-intl"); to force it use the actual one , not mock --- not working.
the react component is: WarningModal.jsx:
import { FormattedMessage, injectIntl } from "react-intl";
.......
const WarningModal = ({
.........
...props
}) => {
........
export default injectIntl(WarningModal);
the intlTestHelper.js file is :
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from "react";
import { IntlProvider, intlShape } from "react-intl";
import { mount, shallow } from "enzyme"; // eslint-disable-line import/no-extraneous-dependencies
/** Create the IntlProvider to retrieve context for wrapping around. */
function createIntlContext(messages, locale) {
const { IntlProvider } = jest.requireActual("react-intl");
const intlProvider = new IntlProvider({ messages, locale }, {});
const { intl } = intlProvider.getChildContext();
return intl;
}
/** When using React-Intl `injectIntl` on components, props.intl is required. */
function nodeWithIntlProp(node, messages = {}, locale = "en") {
return React.cloneElement(node, {
intl: createIntlContext(messages, locale)
});
}
/**
* Create a shadow renderer that wraps a node with Intl provider context.
* #param {ReactComponent} node - Any React Component
* #param {Object} context
* #param {Object} messages - A map with keys (id) and messages (value)
* #param {string} locale - Locale string
*/
export function shallowWithIntl(
node,
{ context } = {},
messages = {},
locale = "en"
) {
return shallow(nodeWithIntlProp(node), {
context: Object.assign({}, context, {
intl: createIntlContext(messages, locale)
})
});
}
/**
* Mount the node with Intl provider context.
* #param {Component} node - Any React Component
* #param {Object} context
* #param {Object} messages - A map with keys (id) and messages (value)
* #param {string} locale - Locale string
*/
export function mountWithIntl(
node,
{ context, childContextTypes } = {},
messages = {},
locale = "en"
) {
return mount(nodeWithIntlProp(node), {
context: Object.assign({}, context, {
intl: createIntlContext(messages, locale)
}),
childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes)
});
}
here how I use it to test:
import React from "react";
import { _WM as WarningModal } from "../components/WarningModal";
// import { shallow } from "enzyme";
import { mountWithIntl } from "../utils/intlTestHelper.js";
describe("<WarningModal />", () => {
const props = {
discardChanges: jest.fn(),
saveChanges: jest.fn(),
closeWarningModal: jest.fn(),
intl: { formatMessage: jest.fn() }
};
it("should have heading", () => {
const wrapper = mountWithIntl(<WarningModal {...props} />);
expect(wrapper.find(".confirm-title")).toBeTruthy();
});
});
error:
● <WarningModal /> › should have heading
TypeError: intlProvider.getChildContext is not a function
14 | const { IntlProvider } = jest.requireActual("react-intl");
15 | const intlProvider = new IntlProvider({ messages, locale }, {});
> 16 | const { intl } = intlProvider.getChildContext();
| ^
17 | return intl;
18 | }
19 |
at getChildContext (src/utils/intlTestHelper.js:16:33)
at createIntlContext (src/utils/intlTestHelper.js:23:11)
at nodeWithIntlProp (src/utils/intlTestHelper.js:60:16)
at Object.<anonymous> (src/tests/WarningModal.spec.js:29:21)
please shine some lights on this. Thank you.
In later versions of react-intl getChildContext has been deprecated and may generate this error. You can use the following instead:
import { createIntl } from 'react-intl';
const intl = createIntl({ locale: "en",
messages: {
message1: "Hello world"
}
});
React-Intl has replaced IntlProvider.getChildContext, with the createIntl for testing purpose, while migrating V2 to V3.
We've removed IntlProvider.getChildContext for testing and now you can use createIntl to create a standalone intl object outside of React and use that for testing purposes. See Testing with React Intl for more details
Here is the Link
So the working code for this is
For resolving this error, you have to create custom shallow component. Like as
import { createIntl } from 'react-intl';
const LocalLanguage = {
french:{},
arabic:{},
english:{}
}
const lang = getCurrentLanguage('en', LocalLanguage);
const intl = createIntl({ locale: 'en', lang }, {});
export const shallowWithIntl = (node) => {
return shallow(nodeWithIntlProp(node), { context: { intl } });
}
If this not helps, then you can define the following function, in your helper file.
const messages = require('./Lang/en.json') // en.json
const defaultLocale = 'en'
const locale = defaultLocale
export const intl = (component) => {
return (
<IntlProvider
locale={locale}
messages={messages}
>
{React.cloneElement(component)}
</IntlProvider>
);
}
And use it in your test files as below
const wrapper = mount(intl(<MobileRechargeComponent />));

NetSuite Advanced PDF Creation via Button

I've created a button on an estimate form to print an advanced PDF.
However, I get the below error in the log
java.lang.java.lang.StringIndexOutOfBoundsException: String index out of range: 0
I've read somewhere it might have to do with images in the template, but I have tried taking them out and still get the error.
Does anyone have any idea for me about this?
The code to generate/render the PDF is:
* #NApiVersion 2.x
* #NScriptType Suitelet
* #NModuleScope Public
*/
define([
'SuiteScripts/Directory/Library.js'
, 'N/render'
, 'N/record'
],
function (Library, render, record)
{
/**
* Main entry function
*
* #param {Object} context
* #returns {Void}
*/
function PrintPriceIncreaseQuote(context)
{
var renderer = null;
try
{
if (context.request.method == 'GET')
{
renderer = createRenderer(context);
printTemplate(context.response, renderer);
}
}
catch (e)
{
Library.errorHandler('PrintPriceIncreaseQuote', e);
}
}
/**
* Create renderer
*
* #param {Object} context
* #returns {Object} renderer
*/
function createRenderer(context)
{
var renderer = null;
var recordId = 0;
try
{
recordId = context.request.parameters.id;
//Create the renderer object
renderer = render.create();
renderer.setTemplateByScriptId('CUSTTMPL_125_4099_SB7_165');
renderer.addRecord({templateName: 'record',
record: record.load({
type: record.Type.ESTIMATE,
id: recordId
})
});
}
catch (e)
{
Library.errorHandler('createRenderer', e);
}
return renderer;
}
/**
* Print merged template
*
* #param {Object} response
* #param {Object} renderer
* #returns {Void}
*/
function printTemplate(response, renderer)
{
var pdfFile = null;
try
{
pdfFile = renderer.renderAsPdf();
response.writeFile({file: pdfFile, isInline: true});
}
catch (e)
{
Library.errorHandler('printTemplate', e);
}
}
return {
onRequest: PrintPriceIncreaseQuote
};
});
'''/**
I tried your code, it works well with my XML/PDF templates. Check the XML DOM structure.

running e2e testing with aurelia cli

I'm trying to implement a few e2e tests in my aurelia-cli app. I've tried looking for docs or blogs but haven't found anything on e2e setup for the cli. I've made the following adjustments to the project.
first I added this to aurelia.json
"e2eTestRunner": {
"id": "protractor",
"displayName": "Protractor",
"source": "test/e2e/src/**/*.ts",
"dist": "test/e2e/dist/",
"typingsSource": [
"typings/**/*.d.ts",
"custom_typings/**/*.d.ts"
]
},
Also added the e2e tasks on aurelia_project/tasks:
e2e.ts
import * as project from '../aurelia.json';
import * as gulp from 'gulp';
import * as del from 'del';
import * as typescript from 'gulp-typescript';
import * as tsConfig from '../../tsconfig.json';
import {CLIOptions} from 'aurelia-cli';
import { webdriver_update, protractor } from 'gulp-protractor';
function clean() {
return del(project.e2eTestRunner.dist + '*');
}
function build() {
var typescriptCompiler = typescriptCompiler || null;
if ( !typescriptCompiler ) {
delete tsConfig.compilerOptions.lib;
typescriptCompiler = typescript.createProject(Object.assign({}, tsConfig.compilerOptions, {
// Add any special overrides for the compiler here
module: 'commonjs'
}));
}
return gulp.src(project.e2eTestRunner.typingsSource.concat(project.e2eTestRunner.source))
.pipe(typescript(typescriptCompiler))
.pipe(gulp.dest(project.e2eTestRunner.dist));
}
// runs build-e2e task
// then runs end to end tasks
// using Protractor: http://angular.github.io/protractor/
function e2e() {
return gulp.src(project.e2eTestRunner.dist + '**/*.js')
.pipe(protractor({
configFile: 'protractor.conf.js',
args: ['--baseUrl', 'http://127.0.0.1:9000']
}))
.on('end', function() { process.exit(); })
.on('error', function(e) { throw e; });
}
export default gulp.series(
webdriver_update,
clean,
build,
e2e
);
and the e2e.json
{
"name": "e2e",
"description": "Runs all e2e tests and reports the results.",
"flags": []
}
I've added a protractor.conf file and aurelia.protractor to the root of my project
protractor.conf.js
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
//seleniumAddress: 'http://0.0.0.0:4444',
specs: ['test/e2e/dist/*.js'],
plugins: [{
path: 'aurelia.protractor.js'
}],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
aurelia.protractor.js
/* Aurelia Protractor Plugin */
function addValueBindLocator() {
by.addLocator('valueBind', function (bindingModel, opt_parentElement) {
var using = opt_parentElement || document;
var matches = using.querySelectorAll('*[value\\.bind="' + bindingModel +'"]');
var result;
if (matches.length === 0) {
result = null;
} else if (matches.length === 1) {
result = matches[0];
} else {
result = matches;
}
return result;
});
}
function loadAndWaitForAureliaPage(pageUrl) {
browser.get(pageUrl);
return browser.executeAsyncScript(
'var cb = arguments[arguments.length - 1];' +
'document.addEventListener("aurelia-composed", function (e) {' +
' cb("Aurelia App composed")' +
'}, false);'
).then(function(result){
console.log(result);
return result;
});
}
function waitForRouterComplete() {
return browser.executeAsyncScript(
'var cb = arguments[arguments.length - 1];' +
'document.querySelector("[aurelia-app]")' +
'.aurelia.subscribeOnce("router:navigation:complete", function() {' +
' cb(true)' +
'});'
).then(function(result){
return result;
});
}
/* Plugin hooks */
exports.setup = function(config) {
// Ignore the default Angular synchronization helpers
browser.ignoreSynchronization = true;
// add the aurelia specific valueBind locator
addValueBindLocator();
// attach a new way to browser.get a page and wait for Aurelia to complete loading
browser.loadAndWaitForAureliaPage = loadAndWaitForAureliaPage;
// wait for router navigations to complete
browser.waitForRouterComplete = waitForRouterComplete;
};
exports.teardown = function(config) {};
exports.postResults = function(config) {};
and I added a sample test in my test/e2e/src folder it doesn't get executed. I've also tried implementing a e2e test within the unit test folder since when I run au test I see that a chrome browser opens up.
describe('aurelia homepage', function() {
it('should load page', function() {
browser.get('http://www.aurelia.io');
expect(browser.getTitle()).toEqual('Home | Aurelia');
});
});
But this throws the error browser is undefined. Am I missing something with e2e testing with the cli? I know aurelia-protractor comes pre-installed but I don't see any way to run it.
I know this is a very late answer, but perhaps for others looking for an answer, you could try to import from the aurelia-protractor plugin
import {browser} from 'aurelia-protractor-plugin/protractor';

How to document module.exports defined with object.defineProperty

I'm using NodeJS and trying to get the JSDoc to property pick up what I'm doing. I have some code that looks like this:
Object.defineProperty(module, 'exports', {
enumerable: true,
configurable: true,
get: function() {
const factory = {};
/**
* Output message to the console
* #param {string} str
*/
factory.foo = function(str) {
console.log(str);
};
return factory;
}
});
Exporting foo the standard way exports.foo = function(str) { ... } is not an option in this case.
Another module can include this module has access to foo (just as if it were exported directly). For example:
var x = require('./x');
x.foo('Hello');
So how can I document this so that jsDoc picks up that this module has a function foo?
I found a way that seems to work:
Object.defineProperty(module, 'exports', {
enumerable: true,
configurable: true,
get: Factory
});
/**
* Get a factory object.
* #returns {Factory}
* #constructor
*/
function Factory() {
var factory = Object.create(Factory.prototype);
/**
* Output a message to the console.
* #name Factory#foo
* #param {string} str
*/
factory.foo = function(str) {
console.log(str);
};
return factory;
}

RequireJS import documentation

Im using in WebStorm editor. My project is using RequireJS with AMD. There is an example of code:
dep.js
define([], function () {
var exports = {
helloWorld: function() {
console.log("Hello world");
}
};
return exports;
});
primary.js
define(['dep'], function (dep) {
var exports = {
sayHello: function() {
dep.helloWorld();
}
};
return exports;
});
How to document properly exports (this mainly described in other answers) and (important!) imports of such AMD modules, so WebStorm can have proper type hints on imported deps (like a "dep" variable in this example).
According to AMD howto, it should be smth like
/**
* #module dep
*/
define([], function() {
/**
* #constructor
* #alias module:dep
*/
var exports = {
helloWorld: function() {
console.log("Hello world");
}
};
return exports;
});

Resources