Testing Backbone with JSDOM - backbone.js

I'm trying to figure out how to test backbone using jsdom and nodeunit as the testing framework.
I've got the error: "Error: Calling node's require("text") failed with error: Error: Cannot find module 'text'"
What means, that the context was not able to load requirejs-text plugin.
I've created the DOM context witn:
var assert = require('assert');
var fs = require('fs');
var index_html = fs.readFileSync(__dirname + '/../static/index.html', 'utf-8');
var requirejs = require('requirejs');
var jsdom = require('jsdom');
// require('amdefine/intercept');
var jQuery = require('jquery');
On the test setUp, on trying to open up the backbone view:
exports.setUp = function(callback){
var document = jsdom.jsdom(index_html);
var window = document.parentWindow;
jsdom.getVirtualConsole(window).sendTo(console);
requirejs.config({
baseUrl: __dirname + '/',
packages: [{
name: 'text',
location: '../node_modules/requirejs-text/text.js ',
main: 'text.js'
},
],
});
requirejs([__dirname + '/../lib/views/stackoverflow.js'], function(bb){
callback();
});
};
The exception is raised on before the callback is called. The view that I'm using is just a regular view using requirejs-text to load the template. I've also created a GitHub Repository just to better explain the issue. Just clone it, enter the project dir and type make. It should reproduce all the steps that I've did.
Thanks in advance!

Related

Refreshing a browser's cache while developing with gulp

My project's setup uses a combination of python's Flask on the backend which serves a fairly simple javascript React webpage using gulp.
Whether I'm debugging frontend code through Chrome or Firefox, I have to do a hard refresh multiple times before the changes make it to the browser. I see the gulp console log Finished 'transform' after N ms after each save, which leads me to believe it's the browsers fault.
I am not a front end engineer so I'm wondering what more experienced devs use. Hitting Cmd+Shift+R 5-20 times after each save is a little mind bogglingly inefficient.
current gulpfile.js:
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
size = require('gulp-size'),
del = require('del'),
babelify = require('babelify'),
source = require('vinyl-source-stream'),
gutil = require('gulp-util');
var compiled_dir = './static/scripts/jsc';
var js_dir = './static/scripts/js';
function handle_error(err) {
gutil.log(err.message);
gutil.beep();
return process.exit(2);
}
gulp.task('transform', function () {
browserify({ entries: js_dir + '/main.js', debug: true })
.transform(babelify)
.bundle()
.on('error', handle_error)
.pipe(source('main.js'))
.pipe(gulp.dest(compiled_dir));
browserify({ entries: js_dir + '/userMgmt.js', debug: true })
.transform(babelify)
.bundle()
.on('error', handle_error)
.pipe(source('userMgmt.js'))
.pipe(gulp.dest(compiled_dir));
});
gulp.task('clean', function (cb) {
del([compiled_dir], cb);
});
gulp.task('default', ['clean'], function () {
gulp.start('transform');
gulp.watch(js_dir + "/*", ['transform']);
});
Method 1: Use this gulp-cache package to disable cache in development mode.
This will work:
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var cache = require('gulp-cache');
gulp.task('default', function () {
return gulp.src('src/index.html')
.pipe(gulp.task('clear', function (done) {
return cache.clearAll(done);
});)
.pipe(usemin({
js: []
}))
.pipe(gulp.dest('dist'));
});
If you don't know how to use it, please update your question with gulp config file, I will configure you that.
Method 2: Configure your watcher.
$ npm install browser-sync --save-dev
var browserSync = require('browser-sync').create();
gulp.watch(['./**/*.{scss,css,html,py,js}'], ['clearCache', browserSync.reload]);
gulp.task('clearCache', function (done) {
return cache.clearAll(done);
});

Getting Error message "RegistrationPO is not a constructor" on log using Protractor

When i am executing my spec file(given below) ,I am getting the error message "RegistrationPO is not a constructor" ,Plz help me to solve my query.Thanks in advance.
//Registration_spec//
'use strict';
var FunLib = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Function_Lib.js'); //Write the location of your javascript file
var RegistrationPO = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Registration_PO.js'); //Write the location of your javascript file
var testData = require('./FFtestdata_Dev_p.json');
describe('Registration: ', function() {
var FuncLib;
var Registration;
var URL;
var EC = protractor.ExpectedConditions;
FuncLib = new FunLib();
Registration = new RegistrationPO();
beforeEach(function () {
browser.ignoreSynchronization = true;
});
//Scenario 1: Open browser :working
it('1-Open the web browser',function(){
browser.ignoreSynchronization = true;
browser.get('Http://dev.forfirm.com:3000');
browser.sleep(200000);
});
});
var FunLib = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Function_Lib.js'); //Write the location of your javascript file
var RegistrationPO = require('/Users/acer/AppData/Roaming/npm/node_modules/protractor/FFAutomation/Registration_PO.js'); //Write the location of your javascript file
Why do you trying to find your pageObjects in node_modules/protractor?
With this you will lose everything on every node_modules reinstall.
I believe this is the reason why you getting errors - you cant import, because file does not exist there
Create more plain structure, something like
node_modules/...all your dependencies will be installed here
utils/Function_Lib.js
pageobjects/Registration_PO.js
specs/registration.spec.js
package.json
protractor.config.js
Then your imports in specs/registration.spec.js will be something like this:
var FunLib = require('../utils/Function_Lib.js');
var RegistrationPO = require('../pageobjects/Registration_PO.js');
Also check what you are exporting in Registration_PO.js and Function_Lib.js

Marionette - error on call of Layout extend Marionette.LayoutView.extend

In my app, I am using Marionette the extension of Backbone. I installed backbone + marionette with using NPM and Browserify. I am getting as a first error as :
Uncaught TypeError: Cannot read property 'extend' of undefined
driver.js
require('./setup.js');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var TodoList = Backbone.Marionette.LayoutView.extend({
el: '#app-hook',
template: require('./app/templates/layout.html')
});
var todo = new TodoList({
model: new Backbone.Model({
items: [
{assignee: 'Scott', text: 'Write a book about Marionette'},
{assignee: 'Andrew', text: 'Do some coding'}
]
})
});
todo.render();
compile project with command browserify driver.js -t node-underscorify -o static/app.js Whithout errors.
Please any help me. Thank you.
Can you confirm the version of Marionette you are using? If it's version 3 LayoutView was removed and you should use View instead:
var TodoList = Backbone.Marionette.View.extend({
el: '#app-hook',
template: require('./app/templates/layout.html')
});
You can read about more changes in their upgrade guide.

Change script type to "text/babel" using requireJS

I am using requireJS to load React components but I was getting the error "Uncaught SyntaxError: Unexpected token <" because the script type for the file is "text/javascript" instead of "text/babel". To solve this I have tried to set the scriptType as explained by requireJS docs and explained in this question, but I'm unable to get it working or find a good example of how to make this work.
requireConfig.js:
requirejs.config({
baseUrl: 'scripts/',
paths:
{
jquery: 'jquery-1.9.0',
react: 'libs/build/react',
reactdom: 'libs/build/react-dom',
browser: '//cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min',
inputWindow: 'inputWindow/inputWindow'
},
scriptType: {
'inputWindow': "text/babel"
}
});
define(function (require) {
var InputWindow = require('inputWindow');
InputWindow.initialize();
});
inputWindow.js:
define(function(require){
var React = require('react');
var ReactDOM = require('reactdom');
var InputWindow = React.createClass({
render: function(){
return(<div>
{this.props.message}
</div>)
}
});
function initialize(){
ReactDOM.render(<InputWindow message="Hello World!"/>, document.getElementById('inputWindowDiv'))
}
return {
initialize: initialize,
}
})
When I configure requireConfig.js with the section
scriptType:{
'inputWindow':'text/babel'
}
then the file inputWindow.js is loaded into index.html with the tag
type="[Object Object]"
until requireJS times out.
screen capture of inputWindow.js loaded with type=[Object Object]
Instead of
scriptType: {
'inputWindow': "text/babel"
}
try
scriptType: 'text/babel'
It should work. Right now you're trying to stringify an object so no wonder it doesn't work. ;)

Can I apply Flux architecture with ReactJS.net?

How create flux architecture in asp.net using reactjs.net ?
I will have several files. Jsx, how will I manage to be all rendenizador by the server?
In this example => Link, it creates using asp.net but not render with server
I am currently working on a feature as a test bed for reactjs + flux in our .net application. Here is how it is set up.
We use nodejs as a package manager. we use NodeJs Visual Studio Tools to get the nodejs interactive window in VS and to be able to create NodeJs projects. http://nodejstools.codeplex.com/
Gulp task calls browserify to search through the the root jsx and find all dependencies. Gulp also calls the reactify library is used to transform the jsx files. The concatenated .js file is put on in a directory in our mvc website.
Gulp task copies all relevant js files to the mvc.net project as well.
When developing we use the Visual Studio Task Runner extension to run a Gulp task that watches for changes so we don't have to "keep building" while developing. It uses the "watchify" library.
We use Jest for testing - although we had an issue with NodeJs and jest playing nice in the newest version of NodeJs, so we had to down grade to 0.10.36.
we use TeamCity to run the Gulp task before building our solution (have a test setup, but haven't added it to my new feature yet).
Gulp does most of the magic. Here is a copy of our Gulp file (it is messy, but I am still learning). Many of the tasks are to watch css js and jsx files, but I hope this helps.
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var concat = require('gulp-concat');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var createbundler = function () {
var bundler = browserify({
entries: ['./app/js/VaeApp.jsx'], // Only need the root js file, browserify finds the dependencies
transform: [reactify], // We want to convert JSX to normal javascript
debug: false, // include sourcemapping for minified scripts?
cache: {}, packageCache: {}, fullPaths: true // Requirement of watchify
});
return bundler;
}
gulp.task('js', function () {
var bundler = createbundler();
bundler.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())// <----- convert from streaming to buffered vinyl file object
.pipe(uglify())
// Create the initial bundle when starting the task
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
});
gulp.task('js-shim-sham', function () {
gulp.src('./node_modules/es5-shim/es5-*.min.js')
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
console.log("updated shim-sham");
});
gulp.task('js-dev', function () {
var watcher = watchify(createbundler());
return watcher
.on('update', function () { // When any files update
var updateStart = Date.now();
console.log('Updating!');
watcher.bundle().pipe(source('bundle.js'))
.pipe(buffer())// <----- convert from streaming to buffered vinyl file object
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
})
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())// <----- convert from streaming to buffered vinyl file object
// .pipe(uglify())
// Create the initial bundle when starting the task
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/js'));
});
var runcss = function () {
var updateStart = Date.now();
gulp.src('./app/css/document/*.css')
.pipe(concat('main.css'))
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/css'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
};
var runimages = function () {
var updateStart = Date.now();
gulp.src('./app/img/*.*')
.pipe(gulp.dest('../Mvc.Web/Scripts/Flux/img'));
console.log('Updated!', (Date.now() - updateStart) + 'ms');
};
gulp.task('styles', function () {
runcss();
runimages();
});
gulp.task('styles-dev', function () {
runcss();
gulp.watch('./app/css/document/*.css', runcss);
runimages();
gulp.watch('./app/img/*.*', runimages);
});
// Just running the two tasks
gulp.task('build-dev', ['js-dev', 'styles-dev', 'js-shim-sham']);
// Just running the two tasks
gulp.task('build', ['js', 'styles', 'js-shim']);
Check out react-dot-not.
It uses webpack/gulp with ASP.MVC. it supports redux/flux, supports client side routing with react-router, with an F5 at any time to re-render the same page from the server.

Resources