Require.JS and JS Test Driver: Unexpected token < - coffeescript

I am trying to test a simple Backbone Model loaded via RequireJS:
define ["backbone"], (Backbone)->
class Todo extends Backbone.Model
defaults:
title: ''
priority: 0
done: false
validate: (attrs) ->
errs = {}
hasErrors = false
if (attrs.title is "")
hasErrors = true
errs.title = "Please specify a todo"
if hasErrors
return errs
toggleDone: ->
#save("done", !#get("done"))
return Todo
My tests look like:
requirejs.config
baseUrl: "js/"
paths:
jquery: "https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min"
jqueryui: "https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min"
json2: "http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2"
underscore: "http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min"
backbone: "http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min"
backboneLocalStorage: "https://raw.github.com/jeromegn/Backbone.localStorage/master/backbone.localStorage-min"
shim:
"underscore":
exports: "_"
"backbone":
deps: ["jquery", "underscore", "json2"]
exports: "Backbone"
"jqueryui":
deps: ["jquery"]
"backboneLocalStorage":
deps: ["backbone"]
exports: "Backbone.LocalStorage"
require ["models/todo"], (Todo) ->
console.log Todo
TodoTests = TestCase("TodoTests")
TodoTests::testCreateTodo = ->
todo = new Todo({ title: "Hello" })
assertEquals "Hello", todo.get("title")
assertEquals 0, todo.get("priority")
assertEquals false, todo.get("done")
The JS Test Driver config:
server: http://localhost:3001
load:
- ../public/js/libs/require.js
- ../public/js/tests.js
serve:
- ../public/js/models/*
- ../public/js/collections/*
- ../public/js/views/*
Problem seen from the JS Test Driver listened page on Chrome console:
Uncaught SyntaxError: Unexpected token <
Looking at Todo.js from Chrome,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Console Runner</title><script type="text/javascript">var start = new Date().getTime();</script>
Uncaught SyntaxError: Unexpected token <
<script src="/static/lib/json2.js" type="text/javascript"></script><script src="/static/lib/json_sans_eval.js" type="text/javascript"></script><script src="/static/jstestdrivernamespace.js" type="text/javascript"></script><script src="/static/lib/jquery-min.js" type="text/javascript"></script><script src="/static/runner.js" type="text/javascript"></script><script type="text/javascript">jstestdriver.runConfig = {'debug':false};</script>
<script type="text/javascript">jstestdriver.console = new jstestdriver.Console();
Notice its a HTML page instead of my actual JS. Also console.log(Todo) returns undefined since a HTML page is returned in place of a JS. Did I configure this wrongly?

I struggled with this for days and searched with Google endlessly until I finally found out what JsTestDriver was doing. In your requirejs.config, for your tests to run properly, your baseUrl needs to be:
baseUrl: /test/path/to/your/stuff
The reason is when JsTestDriver makes its server, it prepends /test/ to all the directories. If the baseUrl isn't set properly, it starts trying to send back local a reference to window I think.
The only other problem that I see you may run into is running the tests with the require statement as the first line. I have Jasmine and putting my require() at the top of my tests caused them to never run so I had to do it in my beforeEach for my tests and get the object before they ran.
I'm probably doing something wrong though I see countless other people claiming that the require statement in Jasmine works, so my hunt continues.

Have you checked your ajax responses? I just had the same thing and that '<' was from the opening doctype tag that was returned when the resource 404'd...

Related

Using a Svelte build with a Sails node server

I am trying to set up a website with Svelte for the frontEnd and Sails for the backend.
My problem is that I can't display my Svelte public build as my Sails default web page.
I want to keep the organization below (or maybe something similar) and have my Svelte public build page when I go on 'http://myserver:1337' instead of having the default Sails page : file organization
PS: I am using Node: v14.4.0, Sails: v1.2.4 and Svelte: v6.14.5.
Thank you all :)
You could try something like:
Compile Svelt to build into the /public directory on Sails.js.
Open your rollup.config.js and change the path of your public/build/bundle.js and public/build.bundle.css to the public sails path, i.e. "../server/public...".
Configure /task/pipeline.js to include the compiled js and css files:
// tasks/pipeline.js
var cssFilesToInject = [
'css/**/global.css',
'css/**/bundle.css',
'css/**/*.css',
];
var jsFilesToInject = [
'js/**/bundle.js',
'js/**/*.js'
];
Create a controller to load the index file:
// router.js
'/*': { action: 'index', skipAssets: true, skipRegex: /^\/api\/.*$/ },
The excluded "/api" routes is to allow you to configure the CRUD routes.
The index controller:
module.exports = {
friendlyName: 'View homepage',
description: 'Display a compiled index page',
exits: {
success: {
statusCode: 200,
viewTemplatePath: 'pages/index'
},
},
fn: async function () {
return {};
}
};
And the index page you could include the template index.html or create your own index.ejs to load the static content, the same you configured before:
// views/templates/template.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Svelte app</title>
<link rel='icon' type='image/png' href='/favicon.png'>
<!--STYLES-->
<!--STYLES END-->
</head>
<body>
<!--TEMPLATES-->
<!--TEMPLATES END-->
<%- body %>
<!-- exposeLocalsToBrowser ( ) %>
<!--SCRIPTS-->
<!--SCRIPTS END-->
</body>
</html>
And the index.ejs:
// views/pages/index.ejs
<!-- Nothing here I mean -->
Thank you for your answer it helps me to understand how does it works.
I am sorry but I did not follow your tutorial exactly (because I was not able to understand what I was supposed to do ;) ).
I edit the rollup.config.js as :
import svelte from 'rollup-plugin-svelte';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
const production = !process.env.ROLLUP_WATCH;
const BUILD_PATH = '../server/assets';
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: `${BUILD_PATH}/build/bundle.js`
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write(`${BUILD_PATH}/build/bundle.css`);
}
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload(BUILD_PATH),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
And I move my files is the assets as :
file organization
Then I deleted the homepage.ejs in server/views/pages/
And it works :) !
Thank you again for your quick answer

Protractor+Mocha fails suite with TypeError before browser loads SUT

Context
I'm exploring angular2 + angular-cli + typescript. My objective is to ensure that if I am doing an angular app or a node app in typescript I would be using the same testing technologies as legacy node apps that use mocha. To this end I am trying to reconfigure the angular-cli generated protractor.conf.js to use mocha instead of jasmine.
Question
How do you properly integrate angular-cli + mocha + protractor so that tests will execute with protractor actually providing the mocha specs useful browser/element/by components?
I've already changed the protractor.conf.js to use mocha and chai and the tests complete, however all interactions with protractor components fail i.e. element(by.css('app-root h1')).getText().
converted protractor.conf.js
exports.config = {
allScriptsTimeout: 11000, // The timeout for a script run on the browser.
specs: [
'./e2e/**/*.e2e-spec.ts' // pattern for the test specs
],
baseUrl: 'http://localhost:4200/', // base url of the SUT
capabilities: {
'browserName': 'chrome' // browser to use
},
directConnect: true, // selenium will not need a server, direct connet to chrome
framework: 'mocha', // Use mocha instead of jasmine
mochaOpts: { // Mocha specific options
reporter: "spec",
slow: 3000,
ui: 'bdd',
timeout: 30000
},
beforeLaunch: function() { // Do all the typescript
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
},
onPrepare: function() {}
};
Suspicion
It feels like the issue is that the suite is executing (and failing) before the the browser has even loaded the app. This could be the protractor/browser interaction which from what I understand should be agnostic to the spec that's being used. Perhaps this understanding is incorrect?
Example Source
I have a running example on GitHub which I am using to test and compare the conversion
Broken branch using mocha
Working master using jasmine
Investigation so far
Running protractor (via node) on the command line node node_modules\protractor\bin\protractor protractor.conf.js --stackTrace --troubleshoot shows us that the suite is configured and running with a truthy test, a skipped test, and the actual application tests
Suite results
We see that the truthy test is passing, the skipped test is skipped, and the application tests all fail with the same sort of error
1 passing
1 pending
5 failing
1) A descriptive test name that is irrelevant to the error:
TypeError: obj.indexOf is not a function
at include (node_modules\chai\lib\chai\core\assertions.js:228:45)
at doAsserterAsyncAndAddThen (node_modules\chai-as-promised\lib\chai-as-promised.js:293:29)
at .<anonymous> (node_modules\chai-as-promised\lib\chai-as-promised.js:271:25)
at chainableBehavior.method (node_modules\chai\lib\chai\utils\overwriteChainableMethod.js:51:34)
at assert (node_modules\chai\lib\chai\utils\addChainableMethod.js:84:49)
at Context.it (e2e\search\search.e2e-spec.ts:14:40)
at runTest (node_modules\selenium-webdriver\testing\index.js:166:22)
at node_modules\selenium-webdriver\testing\index.js:187:16
at new ManagedPromise (node_modules\selenium-webdriver\lib\promise.js:1067:7)
at controlFlowExecute (node_modules\selenium-webdriver\testing\index.js:186:14)
From: Task: A descriptive test name that is irrelevant to the error
at Context.ret (node_modules\selenium-webdriver\testing\index.js:185:10)
It appears that the TypeError would be caused because the app itself never seems to have to time to actually load in the browser before the suite is complete
--troubleshoot output
[09:26:33] D/launcher - Running with --troubleshoot
[09:26:33] D/launcher - Protractor version: 5.1.1
[09:26:33] D/launcher - Your base url for tests is http://localhost:4200/
[09:26:33] I/direct - Using ChromeDriver directly...
[09:26:36] D/runner - WebDriver session successfully started with capabilities Capabilities {
'acceptSslCerts' => true,
'applicationCacheEnabled' => false,
'browserConnectionEnabled' => false,
'browserName' => 'chrome',
'chrome' => { chromedriverVersion: '2.28.455520 (cc17746adff54984afff480136733114c6b3704b)',
userDataDir: 'C:\\Users\\abartish\\AppData\\Local\\Temp\\scoped_dir4596_5000' },
'cssSelectorsEnabled' => true,
'databaseEnabled' => false,
'handlesAlerts' => true,
'hasTouchScreen' => false,
'javascriptEnabled' => true,
'locationContextEnabled' => true,
'mobileEmulationEnabled' => false,
'nativeEvents' => true,
'networkConnectionEnabled' => false,
'pageLoadStrategy' => 'normal',
'platform' => 'Windows NT',
'rotatable' => false,
'takesHeapSnapshot' => true,
'takesScreenshot' => true,
'unexpectedAlertBehaviour' => '',
'version' => '56.0.2924.87',
'webStorageEnabled' => true }
[09:26:36] D/runner - Running with spec files ./e2e/**/*.e2e-spec.ts
Additional Info
Interestingly enough, if you run protractor with elementExplorer node node_modules\protractor\bin\protractor protractor.conf.js --stackTrace --troubleshoot --elementExplorer it will not run the tests but we do see the SUT resolve in the browser that gets launched. This I can't explain.
First off, I am not that familiar with Mocha. However, I can get your tests to pass. This is what you'll need to do:
Set your dependencies
It sometimes is great to roll with the latest and greatest dependencies. The latest chai-as-promised did not work for me. I once tried to update the Protractor dependencies to the latest version of chai and chai-as-promised and ran issues. I had to downgrade your dependencies and ended up working with:
"chai": "~3.5.0",
"chai-as-promised": "~5.3.0",
These are the same versions as the Protractor package.json.
Use the onPrepare plugin
Set chai-as-promised before Protractor runs the test:
onPrepare: function() {
let chai = require('chai');
let chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
global.chai = chai;
}
Edit the test:
Add or modify the following.
app.e2e-spec.ts
import {RootPage} from './root/root.po';
let expect = global["chai"].expect;
// change the following lines to have "eventually"
expect(page.getParagraphText()).to.eventually.contain('Car search POC');
// if you don't want to use "eventually"
page.getParagraphText().then(paragraph => {
expect(paragraph).to.contain('Car search POC');
});
root.e2e-spec.ts:
let expect = global["chai"].expect;
describe('Home page', () => {
// change the following lines to have "eventually"
expect(page.getParagraphText()).to.eventually.include('Car search POC');
expect(browser.getCurrentUrl()).to.eventually.include(homePage.uri());
home.e2e-spec.ts:
import {RootPage} from './root.po';
import {HomePage} from '../home/home.po';
import {WaitCondition} from '../wait.conditions';
let expect = global["chai"].expect;
// change the following lines to have "eventually"
expect(page.getParagraphText()).to.eventually.equal('Car search POC');
// This line will not work. getInnerHtml has been deprecated by both
// Protractor and selenium-webdriver.
//
// If you want to use something similar, do something like:
// let i = browser.executeScript("return arguments[0].innerHTML;", element(locator));
// This is noted in the CHANGELOG under the Protractor 5.0.0 release
expect(page.getListingContent()).to.exist;
search.e2e-spec.ts
import {SearchPage} from './search.po';
let expect = global["chai"].expect;
// change the following lines to have "eventually"
expect(page.getParagraphText()).to.eventually.contain('Car search POC');
Console output
Here is my results from running your test. Note that "will have content" fails because getInnerHtml() is not a valid.
angular-cli-seed App
✓ will do normal tests
✓ will display its title
Home page
✓ will display its title
- will have content
root page
✓ will display its title
✓ will redirect the URL to the home page
search page
✓ will display its title
6 passing (5s)
1 pending
This was a fun StackOverflow question to go through. It was easy to answer since you included a branch of what was not working. Happy testing!

jquery in didInsertElement jshint error

when using jquery inside the component callback, the callback function for click
understands $ directly, and is working with $, but there is a jshint error
components/xxx.js: line 13, col 17, '$' is not defined.
Using this.$ inside the jquery click callback gives an error at run time
import Ember from 'ember';
export default Ember.Component.extend({
didInsertElement() {
this._super(...arguments);
this.$()
.on('click', function() {
$('.class').something(); //ok but jshint error
this.$('.class').something();//jshint ok but error at run time
});
}
});
Thanks
use this at the top of the file
/* globals $ */
Another approach is to set the following configuration to .jshintrc in the root of your app that prevents checking for the whole app which tells jshint that there are two global variables:
{
"globals": {
"$": false,
"jQuery": false
}
}
Note: If you like you can also use the jQuery version as same as Ember jQuery by changing
$('.class').something(); //ok but jshint error
to
Ember.$('.class').something();
which probably drops that error as well.

Protractor & Cucumber. this.visit is not a function

I'm trying to experiment with protractor and cucumber to add some functional BDD testing to some of our webapps. Piecing together the scraps of information online related to this process, I've managed to piece together a very basic test but when I run the tests with protractor conf.js I get the following error
this.visit is not a function
I'm sure this is something I am doing fundamentally wrong but could someone show me the error of my ways, please?
The full console for this test reads:
Using the selenium server at http://192.168.12.100:4724/wd/hub
[launcher] Running 1 instances of WebDriver
Feature: Example feature
As a user of cucumber.js
I want to have documentation on cucumber
So that I can concentrate on building awesome applications
Scenario: Reading documentation # features/homepage.feature:6
Given I am on the Cucumber.js GitHub repository # features/homepage.feature:7
TypeError: this.visit is not a function
at World.<anonymous> (/Users/fraserh/Documents/WorkingDir/protractor/features/homepageSteps.js:14:11)
at doNTCallback0 (node.js:407:9)
at process._tickCallback (node.js:336:13)
When I go to the README file # features/homepage.feature:8
Then I should see "Usage" as the page title # features/homepage.feature:9
(::) failed steps (::)
TypeError: this.visit is not a function
at World.<anonymous> (/Users/fraserh/Documents/WorkingDir/protractor/features/homepageSteps.js:14:11)
at doNTCallback0 (node.js:407:9)
at process._tickCallback (node.js:336:13)
Failing scenarios:
features/homepage.feature:6 # Scenario: Reading documentation
1 scenario (1 failed)
3 steps (1 failed, 2 skipped)
[launcher] 0 instance(s) of WebDriver still running
[launcher] chrome #1 failed 1 test(s)
[launcher] overall: 1 failed spec(s)
[launcher] Process exited with error code 1
I have the following structure:
conf.js
features/homepage.feature
features/homepageSteps.js
conf.js
exports.config = {
framework: 'cucumber',
seleniumAddress: 'http://192.168.12.100:4724/wd/hub', //this is a working selenium instance
capabilities: {
'browserName': 'chrome'
},
specs: ['features/homepage.feature'],
cucumberOpts: {
require: 'features/homepageSteps.js',
format: 'pretty'
}
};
homepage.feature
Feature: Example feature
As a user of cucumber.js
I want to have documentation on cucumber
So that I can concentrate on building awesome applications
Scenario: Reading documentation
Given I am on the Cucumber.js GitHub repository
When I go to the README file
Then I should see "Usage" as the page title
homepageSteps.js
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
var that = this;
this.Given(/^I am on the Cucumber.js GitHub repository$/, function (callback) {
// Express the regexp above with the code you wish you had.
// `this` is set to a new this.World instance.
// i.e. you may use this.browser to execute the step:
this.visit('https://github.com/cucumber/cucumber-js', callback);
// The callback is passed to visit() so that when the job's finished, the next step can
// be executed by Cucumber.
});
this.When(/^I go to the README file$/, function (callback) {
// Express the regexp above with the code you wish you had. Call callback() at the end
// of the step, or callback.pending() if the step is not yet implemented:
callback.pending();
});
this.Then(/^I should see "(.*)" as the page title$/, function (title, callback) {
// matching groups are passed as parameters to the step definition
var pageTitle = this.browser.text('title');
if (title === pageTitle) {
callback();
} else {
callback.fail(new Error("Expected to be on page with title " + title));
}
});
};
It looks like you took the code example from here: https://github.com/cucumber/cucumber-js
And you missed the next piece of code where this.visit function is created:
// features/support/world.js
var zombie = require('zombie');
function World() {
this.browser = new zombie(); // this.browser will be available in step definitions
this.visit = function (url, callback) {
this.browser.visit(url, callback);
};
}
module.exports = function() {
this.World = World;
};
You will need to install zombie package as well:
npm install zombie --save-dev

browserify/karma/angular.js "TypeError: Cannot read property '$injector' of null" when second test uses "angular.mock.inject", "currentSpec" is null

I have an Angular.js app and am experimenting with using it with Browserify. The app works, but I want to run tests too, I have two jasmine tests that I run with karma. I user browserify to give me access to angular.js and angular-mocks.js and other test fixtures within the tests.
Versions are:-
"angular": "^1.4.0",
"angular-mocks": "^1.4.0",
"browserify": "^10.2.3",
"karma": "^0.12.32",
"karma-browserify": "^4.2.1",
"karma-chrome-launcher": "^0.1.12",
"karma-coffee-preprocessor": "^0.2.1",
"karma-jasmine": "^0.3.5",
"karma-phantomjs-launcher": "^0.1.4",
If I run the tests individually (by commenting one or the other from the karma.conf file) they both work OK. (yey!)
But if I run them both I get this error
TypeError: Cannot read property '$injector' of null
at Object.workFn (/tmp/3efdb16f2047e981872d82fd8db9c0a8.browserify:2272:22 <- node_modules/angular-mocks/angular-mocks.js:2271:0)
looking at line 2271 of the angular.mocks.js It reads
if (currentSpec.$injector) {
So clearly currentSpec is somehow now null.
I have isolated the problem to when I call "angular.mock.inject" in the second test.
beforeEach(angular.mock.inject(function (_GridUtilService_) {
gridUtilService = _GridUtilService_;
}));
If I comment this out it works, but obviously I can't then run a test n my gridUtilService.
Does anyone know how to run two (or more :-) angular-mock jasmine tests with karma and browserify?
below are my tests, karma.conf file. the Angular services work when deployed but for this purpose they can simply be dumb services that do nothing.
karma.conf:-
// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['browserify', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'src/main/assets/js/**/*.js',
// 'src/test/**/*.js'
'src/test/services/SettingUtil*.js',
'src/test/services/GridUtil*.js'
],
// list of files to exclude
exclude: [
'src/main/assets/js/**/app-config.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/main/assets/js/**/*.js': ['browserify'],
'src/test/**/*.js': ['browserify']
},
browserify: {
debug: true,
extensions: ['.js', '.coffee', '.hbs']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
// browsers: ['PhantomJS', 'Chrome'],
// browsers: ['PhantomJS'],
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
src/test/services/SettingUtilServiceTest.js:
'use strict';
describe("SettingUtilServiceTest.", function() {
it("contains spec with an expectation", function() {
expect(true).toBe(true);
});
require('angular');
require('angular-mocks');
// can't do below see error at https://github.com/xdissent/karma-browserify/issues/10
//beforeEach(module('dpServices'));
//so need todo this
beforeEach(angular.mock.module('dpServices'));
var fixtures = require('./serviceFixtures.js');
var sus = fixtures.settingUtilServiceTestFixtures;
var ts1 = sus.tablesetting1;
var ts2 = sus.tablesetting2;
var settingUtilService;
beforeEach(angular.mock.inject(function (_settingUtilService_) {
settingUtilService = _settingUtilService_;
}));
it('should return an object containing mins and maxs from function minMaxes()', function() {
expect(ts1).toBeDefined();
expect(ts2).toBeDefined();
var minMaxs = settingUtilService.minMaxs(ts1);
var mins = minMaxs.mins;
expect(mins).toBeDefined();
var maxs = minMaxs.maxs;
expect(maxs).toBeDefined();
});
});
src/test/services/GridUtilServiceTest.js:
'use strict';
describe("GridUtilServiceTest.", function() {
it("is a set of tests to test GridUtilService.", function() {
expect(true).toBe(true);
});
require('angular');
require('angular-mocks');
// can't do below see error at https://github.com/xdissent/karma-browserify/issues/10
// beforeEach(module('dpServices'));
//so need todo this
beforeEach(angular.mock.module('dpServices'));
var fixtures = require('./gridFixtures.js');
var gridFix = fixtures.gridUtilServiceTestFixtures;
var ts1 = gridFix.tablesetting1;
var ts2 = gridFix.tablesetting2;
var ts3 = gridFix.tablesetting3;
var gridUtilService;
beforeEach(angular.mock.inject(function (_GridUtilService_) {
gridUtilService = _GridUtilService_;
}));
it('should return an object containing mins and maxs from function minMaxes()', function() {
expect(ts1).toBeDefined();
expect(ts2).toBeDefined();
expect(ts3).toBeDefined();
});
});
If you need access to the angular setup I can provide it (split into multiple files using browserify's require() function and built with gulp... but as I say the app runs ok and the tests only fail when there are two tests, so I think the issue is with karma-jasmine and angular-mocks or overwriting the currentSpec variable.
If anyone knows how to split my angular tests into multiple tests (I don't want a monolithic angular test) without the error message all help is appreciated. thanks.
I had the same issue, the issue for me was because I was requiring angular and angular-mocks exactly as you were inside each describe block. I moved the two lines
require('angular');
require('angular-mocks');
above the describe blocks and made sure to only call them once.