Jasmine Ajax request.respondWith is not working - ajax

I am using Jasmine 2.0.4 with jasmine-ajax 2.99.0 to try to test a module that calls a web service.
The code is the following:
define(['models/data-service', 'models/admin', 'models/contest', 'models/participant', 'ContestResponse'],
function(dataService, admin, Contest, Participant, ContestResponse){
"use strict";
describe("Data Service Tests", function(){
var onSuccess, onFailure, request;
describe("on new contests loaded", function(){
beforeEach(function(){
jasmine.Ajax.install();
});
it("calls onSuccess with an array of Contests", function(){
onSuccess = jasmine.createSpy('onSuccess');
onFailure = jasmine.createSpy('onFailure');
dataService.getContests()
.done(onSuccess)
.fail(onFailure);
request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toBe('/api/contest');
expect(request.method).toBe('GET');
request.respondWith(ContestResponse.getResponse().contest.success);
expect(onSuccess).toHaveBeenCalled();
var successArgs = onSuccess.calls.mostRecent().args[0];
expect(successArgs.length).toEqual(4);
});
});
});
});
Everything works until it reaches the line where I try to call the respondWith method of the request. Even though I can see that the object returned from the jasmine.Ajax.requests.mostRecent() is of type FakeXMLHttpRequest, respondWidth is marked as undefined. Any Ideas?
Thanks
[UPDATE]
I have been able to narrow it down. It looks like the mock-ajax.js file is not being loaded. I have the karma-jasmine-ajax node module installed and have added jasmine-ajax to the frameworks array of the karma.conf.js like this:
frameworks: ['jasmine-ajax','jasmine', 'requirejs'],
is there anything else I need to do?
[RANT] no wonder why so few developers are running unit test with javascript [/RANT]

I faced the same issue, it looks like the latest version doesn't have respondWith method.
Downgrading the jasmine-ajax plugin made the trick:
npm install karma-jasmine-ajax#0.1.1
Now I can see respondWith is working fine.

This appears to have been a transitional problem in one of the jasmine-ajax libraries. Upgrading to latest version (3.1.0 at the time of this writing) will fix your problem.
npm install jasmine-ajax
bower install jasmine-ajax
or
jasmine-ajax on github

If you can't change jasmine-ajax versions due to conflicts (ie: you use Jasmine 1.3 or something else that has a dependency on a different version of jasmine-ajax), you can use: request.response instead of request.respondWith

Related

Vuejs 2 + laravel elixir + lodash Uncaught ReferenceError: _ is not defined

I'm using the tools specified in the title. I import lodash in my bootstrap.js
window._ = require('lodash');
However, when I try to use something like this (similar example to here), I get the error discribed in the title
created() {
this.test();
},
methods: {
test: _.debounce(function () {
console.log('calculating', true);
setTimeout(function () {
console.log('calculating', false);
}.bind(this), 1000)
}, 500),
}
However, if I remove the window._ = require('lodash'); and insert lodash manually in the page it works fine, like
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.js"></script>
What I'm missing?
Also, What is the advantage of importing the libraries by require instead of using Gulp to merge and uglyfy everything?
I am not sure why you are getting that error related to _.
On your other question, I can think following advantage of using require over gulp or any other build tool:
All build tools comes with their own set of dependencies and other accessories, which bloats your overall code size.
You may start to rely on their plugins and time can come, when you need to use grunt for one task, while for other tasks you are using grunt, quting from gulp-grunt
What if your favorite grunt plugin isn't available for gulp yet? Don't fret, there is nothing to worry about! Why don't you just hook in your grunt configuration?
You will have to manage updating of different plugins of gulp and make sure all are working with new updated versions.
These are some of the things I have experienced or read about, but these tools do remove the pain of building, hot-reloading, compressing or obfuscating your code, but definetely there can be other raw way to do these, as what these are doing is providing you an abstraction.

Use onAuthPrompt() with CasperJS and SlimerJS

SlimerJS added a onAuthPrompt callback. Is it possible to get it to work with CasperJS?
I found mention that the phantomjs or slimerjs object is available as casper.page, and then the following answer said that casper.page is only available after calling casper.start(): https://stackoverflow.com/a/16629231/841830
So I tried this code. The onAuthPrompt code is taken from the documentation; I just added a log line to make sure it works.
casper.test.begin("first",function suite(test){
casper.start();
casper.page.onAuthPrompt = function (type, url, realm, credentials) {
console.log("onAuthPrompt: type="+type+",url="+url+",realm="+realm+",credentials="+credentials); //TEMP
credentials.username = "laurent";
credentials.password = "1234";
return true;
};
casper.thenOpen(url,function(){
console.log('Loaded:'+url);
test.assertSelectorHasText('#msg','');
this.capture('1.png');
});
casper.run(function(){test.done();});
});
It loads url (which does not require auth), then an XMLHttpRequest or EventSource connection is made, which is what requires authentication. I see the password prompt pop-up but my onAuthPrompt() function is not getting called.
Am I doing something wrong, or is this not what onAuthPrompt is for, or could it be a bug that I could report (but in that case, do you think the problem is in CasperJS or in SlimerJS?).
According to the documentation, the onAuthPrompt callback was added in version 0.9.0, which has yet to be released.
You can check the documentation from the master branch of the Git repo here.
There is also the latest released documentation (v0.8.3) here

tower.js server.js Bundle error on startup

i am trying to get tower.js up and running. it looks awesome but i'm hitting a snag that seems to have something to do with the package itself.
if i run $tower new myapp or $tower create app myapp i get the following error:
node_modules/tower-server/index.js:46
this.bundle = new Bundle(this);
ReferenceError: Bundle is not defined
when i look at index.js i see a line at the top commented out that defines Bundle:
/**
* Module dependendencies.
*/
var application = {};
var express = require('express');
var sockjs = require('sockjs');
//var Bundle = require('tower-bundle');
var http = require('http');
var instance;`
tower-bundle is not in npm repos. i tried commenting out the Bundle instantiation but then nothing happens. i'm not sure what i'm doing wrong. any help is greatly appreciated.
i should also mention i installed tower and tower-cli globally using npm and i am running node 0.10+ (latest version as of this date.)
One of the maintainers of Tower here. The best way to get help is through Github issues. That's where we're active.
Yes, that command is currently not working. The bundler is also not complete, thus why it was commented out. Right now, we were concentrating mostly on the client-side of things. Right now, there's no use for scaffolding, but we'll be getting the server-side up to standards.
If you need any help, please visit our Github repositories, we'll be glad to help. FYI, the IRC channel is useless right now, we're never on it.

Simple RequireJS in node

I would like to exclusively use RequireJS for node.
I cannot seem to get it all to run in the same file when i run "node r.js file.js":
define('a', function () {
console.log("loaded a");
return {};
});
require(['a'], function(a){
});
is there any way to override define and require strictly with requirejs' definitions.
Also is there a way to do this strictly with r.js and not installing requirejs npm.
You can use require.js in node!
The require.js documentation includes a section on installing require with node.js .
First, you go to the console (assuming you have npm which you should) and type:
npm install requirejs
After that, you're all set up. First you need to require require (no pun intended), so in the top of your main js file, you need something like:
var requirejs = require('requirejs');
Then, you can configure it:
requirejs.config({/*your config with shims,etc goes here*/});
That's it! You can now use it:
requirejs(["module1","module2"],function(mod1,mod2){
//whatever here
});
There are more detailed instructions on this page.
A better solution to the bigger issue:
You can use browserify.
Browserify lets you share code between the client and the server using node.js style require() statements. It shims common things for your like process.nextTick. It even shims modules like path, events and even vm.
I have personally used it in several production projects and it works.

Unable to get jasmine-jquery fixtures to load in Visual Studio with Chutzpah, or even in browser

I'm prototyping a MVC.NET 4.0 application and am defining our Javascript test configuration. I managed to get Jasmine working in VS2012 with the Chutzpah extensions, and I am able to run pure Javascript tests successfully.
However, I am unable to load test fixture (DOM) code and access it from my tests.
Here is the code I'm attempting to run:
test.js
/// various reference paths...
jasmine.getFixtures().fixturesPath = "./";
describe("jasmine tests:", function () {
it("Copies data correctly", function () {
loadFixtures('testfixture.html');
//setFixtures('<div id="wrapper"><div></div></div>');
var widget = $("#wrapper");
expect(widget).toExist();
});
});
The fixture is in the same folder as the test file. The setFixtures operation works, but when I attempt to load the HTML from a file, it doesn't. Initially, I tried to use the most recent version of jasmine-jquery from the repository, but then fell back to the over 1 year old download version 1.3.1 because it looked like there was a bug in the newer one. Here is the message I get with 1.3.1:
Test 'jasmine tests::Copies data correctly' failed
Error: Fixture could not be loaded: ./testfixture.html (status: error, message: undefined) in file:///C:/Users/db66162/SvnProjects/MvcPrototype/MvcPrototype.Tests/Scripts/jasmine/jasmine-jquery-1.3.1.js (line 103)
When I examine the source, it is doing an AJAX call, yet I'm not running in a browser. Instead, I'm using Chutzpah, which runs a headless browser (PhantomJS). When I run this in the browser with a test harness, it does work.
Is there someone out there who has a solution to this problem? I need to be able to run these tests automatically both in Visual Studio and TeamCity (which is why I am using Chutzpah). I am open to solutions that include using another test runner in place of Chutzpah. I am also going to evaluate the qUnit testing framework in this effort, so if you know that qUnit doesn't have this problem in my configuration, I will find that useful.
I fixed the issue by adding the following setting to chutzpah.json:
"TestHarnessLocationMode": "SettingsFileAdjacent",
where chutzpah.json is in my test app root
I eventually got my problem resolved. Thank you Ian for replying. I am able to use PhantomJS in TeamCity to run the tests through the test runner. I contacted the author of Chutzpah and he deployed an update to his product that solved my problem in Visual Studio. I can now run the Jasmine test using Chutzpah conventions to reference libraries and include fixtures while in VS, and use the PhantomJS runner in TeamCity to use the test runner (html).
My solution on TeamCity was to run a batch file that launches tests. So, the batch:
#echo off
REM -- Uses the PhantomJS headless browser packaged with Chutzpah to run
REM -- Jasmine tests. Does not use Chutzpah.
setlocal
set path=..\packages\Chutzpah.2.2.1\tools;%path%;
echo ##teamcity[message text='Starting Jasmine Tests']
phantomjs.exe phantom.run.js %1
echo ##teamcity[message text='Finished Jasmine Tests']
And the Javascript (phantom.run.js):
// This code lifted from https://gist.github.com/3497509.
// It takes the test harness HTML file URL as the parameter. It launches PhantomJS,
// and waits a specific amount of time before exit. Tests must complete before that
// timer ends.
(function () {
"use strict";
var system = require("system");
var url = system.args[1];
phantom.viewportSize = {width: 800, height: 600};
console.log("Opening " + url);
var page = new WebPage();
// This is required because PhantomJS sandboxes the website and it does not
// show up the console messages form that page by default
page.onConsoleMessage = function (msg) {
console.log(msg);
// Exit as soon as the last test finishes.
if (msg && msg.indexOf("Dixi.") !== -1) {
phantom.exit();
}
};
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(-1);
} else {
// Timeout - kill PhantomJS if still not done after 2 minutes.
window.setTimeout(function () {
phantom.exit();
}, 10 * 1000); // NB: use accurately, tune up referring to your needs
}
});
}());
I've got exactly the same problem. AFAIK it's to do with jasmine-jquery trying to load the fixtures via Ajax when the tests are run via the file:// URI scheme.
Apparently Chrome doesn't allow this (see https://stackoverflow.com/a/5469527/1904 and http://code.google.com/p/chromium/issues/detail?id=40787) and support amongst other browsers may vary.
Edit
You might have some joy by trying to set some PhantomJS command-line options such as --web-security=false. YMMV though: I haven't tried this myself yet, but thought I'd mention it in case it's helpful (or in case anyone else know more about this option and whether it will help).
Update
I did manage to get some joy loading HTML fixtures by adding a /// <reference path="relative/path/to/fixtures" /> comment at the top of my Jasmine spec. But I still have trouble loading JSON fixtures.
Further Update
Loading HTML fixtures by adding a /// <reference path="relative/path/to/fixtures" /> comment merely loads in your HTML fixtures to the Jasmine test runner, which may or may not be suitable for your needs. It doesn't load the fixtures into the jasmine-fixtures element, and consequently your fixtures don't get cleaned up after each test.

Resources