Jasmine running on Grunt cant find async functions - javascript

For some reason the async functions (waits, waitsFor, runs) in Jasmine aren't available when I run it from Grunt.
In Grunt:
jasmine:{
pivotal:{
src: 'src/**/*.js',
options:{
specs: 'spec/**/*.spec.js'
}
}
}
In Jasmine spec:
describe('jasmine', function(){
it("should find 'waits'", function(){
waits(1000);
});
it("should find 'waitsFor'", function(){
waitsFor(function(){}, 1000);
});
it("should find 'runs'", function(){
runs(function(){});
});
})
Jasmine output:
jasmine
× should find 'waits'
ReferenceError: Can't find variable: waits in file:///G:/Projects/myproj/spec/test.spec.js (line 3) (1)
× should find 'waitsFor'
ReferenceError: Can't find variable: waitsFor in file:///G:/Projects/myproj/spec/test.spec.js (line 6) (1)
× should find 'runs'
ReferenceError: Can't find variable: runs in file:///G:/Projects/myproj/spec/test.spec.js (line 9) (1)
Am I missing something?

turns out I'm used to using Jasmine 1.3, and the version used by grunt is 2.0. The syntax has changed in 2.0 and the tests need to be written according to the docs on http://jasmine.github.io/2.0/introduction.html

Related

angularjs protractor 3.3.0 not reporting specs

I don't see expected output for a passed run, the assertions are not listed. I expect to see the assertion in this line "1 spec, 0 failures".
The output:
[18:28:06] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[18:28:06] I/launcher - Running 1 instances of WebDriver
Started
.
1 spec, 0 failures
Finished in 0.854 seconds
[18:28:08] I/launcher - 0 instance(s) of WebDriver still running
[18:28:08] I/launcher - chrome #01 passed
Expected end of run output as seen on protractor's web site, http://www.protractortest.org/#/ "Run the test"):
1 test, 3 assertions, 0 failures
The spec:
describe('Viewing index.html', function() {
'use strict';
beforeEach(function(){
browser.get('/');
});
it('should have pages in left nav', function() {
expect(element.all(by.repeater('page in adminClient.selectedSite.pages')).count()).toBeGreaterThan(0);
});
});
I verified that the by.repeater locator worked:
element.all(by.repeater('page in adminClient.selectedSite.pages')).count()
.then(function(count){
console.log('page count: ' + count);
});
[UPDATE] According to this SO, it is a version issue and there is a recommendation to inject jasmine reporters on the onPrepare hook but that created more runtime errors for me.
stack overflow question
My protractor config:
exports.config = {
allScriptsTimeout: 11000,
chromeOnly: true,
chromeDriver: 'node_modules/protractor/bin/selenium/chromedriver_2.21',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['tests/e2e/*-spec.js'],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:8889/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
To see the spec names and assertions you must pass the --verbose flag to protractor. If you are using grunt or something to run protractor, you'll need to specify this flag in your config.
EDIT
After reading your edit I believe I have found the solution to your issue. I've tried it with a project of my own and it appears to work.
The underlying problem is that you are likely using protractor 3, which no longer supports many of the previous options particularly within jasmineNodeOpts. To correct this issue, you should downgrade your version of protractor to 2, the latest version is 2.5.1
Here's the related issue on protractor's github repository. It also mentions a custom reporter within the onPrepare hook like you were talking about, but a different one: jasmine-spec-reporter. I got that working as well with a slightly different configuration than what you are using but it does not display the assertions, just has a much better output for the tests, which I quite like:
jasmineNodeOpts: {
print: function () {} // remove dots for each test
},
onPrepare: function () {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({displayStackTrace: true}));
}

before/afterAll() is not defined in jasmine-node

I'm trying to use the methods beforeAll and afterAll of jasmine, to create a suite of tests with frisby.js, because actually, frisby doesn't have a support for this methods. So, this is what I'm trying to do:
var frisby = require('frisby');
describe("setUp and tearDown", function(){
beforeAll(function(){
console.log("test beforeAll");
});
afterAll(function(){
console.log("afterAll");
});
//FRISBY TESTS
}); //end of describe function
If I change the methods before/afterAll to before/afterEach, is working, but when I'm using before/afterAll this error appears on console:
Message:
ReferenceError: beforeAll is not defined
Stacktrace:
ReferenceError: beforeAll is not defined
I have the jasmine version 2.3.2 installed on my project, so, I don't know what I need to do to integrate this method.
Use the jasmine library not the jasmine-node library. The second one does not support beforeAll and afterAll methods.
1- npm install -g jasmine
2- jasmine init
3- write the test in the spec folder:
describe("A spec using beforeAll and afterAll", function() {
var foo;
beforeAll(function() {
foo = 1;
});
afterAll(function() {
foo = 0;
});
it("sets the initial value of foo before specs run", function() {
expect(foo).toEqual(1);
foo += 1;
});
it("does not reset foo between specs", function() {
expect(foo).toEqual(2);
});
});
4- Run the tests --> jasmine
The current version of frisby doesnt suport this kind of setup. The community, like myself is eager to this feature like in this issue describes.
The team is working on this feature, but it will come in version 2 of the package that is in the way for more than a year now. More info at this link.

Testing Angular with Gulp-mocha: "Window is not Defined"

I am setting up a project with Gulp to run unit tests with Mocha, including Angular tests. I have the basic set up working (indexOf, etc.), however when I include angular-mocks I get this error or a node-module error:
ReferenceError in 'gulp-mocha': "Window is not defined"
I've tried including angular-module-mocks, using gulp-mocha-phantomjs... but the result is the same. (With mocha-phantomjs my error was 'Init timeout'.) I've seen many examples of configurations with Mocha and Angular or Gulp and Karma but have not yet found a solution for Gulp, Mocha and Angular alone.
I'm thinking of something similar to this Karma solution to correctly load angular-mocks by specifying it in a config file and forcing Gulp to load it (Angular testing with Karma: "module is not defined"). However, even if this would work, it seems like gulp-mocha does not support loading a configuration file (mocha.opts - https://github.com/sindresorhus/gulp-mocha/issues/26). I would be happy to hear a more straightforward solution.
I am using angular-mocks 1.2.22 and gulp-mocha 1.1.0.
Code snippets:
var mocha = require('gulp-mocha');
gulp.task('test', function () {
return gulp.src('test/*.js', {read: false})
.pipe(mocha({reporter: 'nyan', timeout: 400}));
});
test/test.js
var assert = require('assert');
var angular_mocks = require('angular-mocks'); //Fails only when this line is present
//tests
What finally worked for me with Gulp/Browserify/Mocha was using Karma and Mocha combined.
Specifically, I used gulp-karma, and defined the configuration at karma.config.js and used a dummy file for gulp.src as others have done:
gulp.task('test', function () {
return gulp.src('./foobar.js').pipe(karma({
configFile:'karma.config.js',
action: 'run'
}))
.on('error', handleErrors);
});
Then I used this karma.config.js file. I needed the npm modules karma-mocha, karma-chai, and karma-bro. (With only the first two, I was getting 'require is not defined'. Then of course I tried including karma-requirejs, but that does not work with Browserify. Then I tried karma-commonjs, which still didn't work. Then I tried karma-browserify, and got a strange error involving bundle() that no one seems to have solved (https://github.com/xdissent/karma-browserify/issues/46). Karma-bro did the trick.)
I also needed to preprocess each file referenced in the tests as well as the tests themselves. (For using phantomJS also include karma-phantomjs-launcher. And I am using the bower version of angular-mocks simply because it is more recent: v1.2.25 compared to 1.2.22 for npm - but the npm version might work.)
module.exports = function(config) {
config.set({
basePath: '',
// frameworks to use
frameworks: ['browserify', 'mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular/lib/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'source/javascript/controllers/*.js',
'source/javascript/*.js',
'test/*.js'
],
reporters: ['progress'],
port: 9876,
colors: true,
autoWatch: true,
browsers: ['PhantomJS'],
preprocessors: {
'source/javascript/controllers/*.js': ['browserify'],
'source/javascript/*.js': ['browserify'],
'test/*.js': ['browserify']
}
});
};
And finally this test passes. At the end I needed to make sure the names of my modules and controllers were consistent (capitals etc.) to resolve 'Module not defined' errors. For debugging I replaced node_modules/angular/lib/angular.min.js with node_modules/angular/lib/angular.js in the files.
describe('Angular', function() {
describe('App Controllers', function() {
beforeEach(angular.mock.module('App'));
describe('MessageCtrl', function() {
it('should retrieve the correct amount of messsages', angular.mock.inject(function($controller) {
var scope = {},
ctrl = $controller('MessageCtrl', {$scope:scope});
assert.equal(scope.messages.length, 2);
}));
});
});
});
I do get this: 'WARNING: Tried to load angular more than once.' I can live with it.

requirejs mocha context error

I have a simple mocha test that fails when using requirejs and the context config.
Here's A.js
define([], function(){
return {};
});
Here's the test spec.js
var requirejs = require('requirejs');
var localReq = requirejs.config({
baseUrl: "./",
context: "context1"
})
describe("context test", function () {
it("should not throw error", function () {
for (var i = 0; i < 100; i++) {
console.log(localReq("A"), i);
}
});
});
When I run the test mocha spec.js, I get the following error:
Uncaught Error: Tried loading "A" at /Users/khirakawa/work/test/node_modules/mocha/bin/A.js then tried node's require("A") and it failed with error: Error: Cannot find module 'A'
Here's a screenshot:
Notice how A was properly loaded and logged 100 times, yet the test still failed. If I comment out the context config, it works just fine.
Mocha is also printing out '1 passing' and '1 failing', even though there is only 1 test.
Why is this happening?
You could write your test like this:
describe("context test", function () {
it("should not throw error", function (done) {
localReq(["A"], function (f) { done(); });
});
});
As you pointed out in a comment, calling localReq to get a module synchronously should work but for some unexplained reason it does not. The code above, which calls localReq to load the module asynchronously, works.
The reason Mocha is saying that your single test is passing and failing is that it is detecting an error that happens after your test is over and has no other test to associate it with. This kind of error message where the same test both passes and fails is a sure indication that you've got something happening asynchronously but that you have not taken care of it in your Mocha test setup.

Chai exports are not found in Mocha test

I have created simple Mocha test. It works perfectly when Node "assert" module is used. I run it from command line (Mocha is installed as a global node module):
$ mocha myTest.js
․
1 test complete (6 ms)
The script looks like this:
var assert = require("assert")
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
Well, I tried to add Chai instead of assert library. I installed it first:
npm install chai
So, the directory node_modules has been created in my project. Great so far. Then, I altered the script to use Chai:
var chai = require("chai");
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
[1,2,3].indexOf(5).should.equal(-1);
expect([1,2,3].indexOf(5)).to.equal(-1);
assert.equal([1,2,3].indexOf(5),-1);
})
})
});
It does not work, Mocha test fails with TypeError:
TypeError: Cannot call method 'equal' of undefined
I assume Chai did not define should so it is undefined.
How is this possible?
How can I make my tests run with Chai? I have tried to install Chai globally with no effect. I also ran the script with -r chai with no effect as well.
Apparently, Chai module is loaded, but does not define the variables (Object.prototype properties). How can I fix this?
var expect = require('chai').expect;
That will get your expect calls working. However, you also have a should call which comes from a different library entirely, so change
[1,2,3].indexOf(5).should.equal(-1);
to
expect([1,2,3].indexOf(5)).to.equal(-1);

Categories