Webpack / Babel / Karma does not complain if test files are invalid - karma-runner

How do I make webpack and karma fail on babel transpiling errors?
Pretty standard setup loading test files like so:
var context = require.context('./app', true, /\.test\.js$/);
context.keys().forEach(context);
Given I have these two test:
describe('Success', () => {
it('should pass', () => {
expect(true).toEqual(true)
});
});
and
describe('Failure', () => {
it('should fail', () => {
expect(true).toEqual(false)
});
});
Then all works well:
Suites and tests results:
- Failure :
* should fail : failed
- Success :
* should pass : ok
Browser results:
- PhantomJS 1.9.8: 2 tests
- 1 ok, 1 failed
BUT if I invalidate the failing test (removing the closing brackets from the Describe call):
describe('Failure', () => {
it('should fail', () => {
expect(true).toEqual(false)
});
Then rather than getting a break I just get:
Suites and tests results:
- Success :
* should pass : ok
Browser results:
- PhantomJS 1.9.8: 1 tests
- ok
It's like the whole test file didn't exist. This is really problematic as with a large test suite an accidental keystroke in a random test file can cause the whole test to be ignored and a possibly failing build to succeed.
I tried configuring the setting the bail option to true in my karma.config:
webpack: {
bail:true,
But made no difference.
How do I make webpack and karma fail on babel transpiling errors?

Related

vitest + msw / testing reactQuery (axios) hooks using renderHook / unable to avoid error logging from test suite

Using a custom logger as follow for our test suite :
export const queryClient = new QueryClient({
logger: {
log: console.log,
warn: console.warn,
error: () => {}
}
});
Mocking errors as follow within msw :
rest.get('/some/api/route', (_req, res, ctx) => {
return res.once(ctx.status(500), ctx.json({ errorMessage: 'some error' }));
})
We override the handlers for errors :
it("should return error", () => {
server.use(...errorHandlers);
const { result } = renderHook(() =>
query({
url: '/some/api/routes',
options: { retry: false }
})
);
...some assertions
});
Out tests are ok, but the network errors are still appearing in the console when running the test suite (the display is thrashed) :
Error: Request failed with status code 500
at createError (.../node_modules/axios/lib/core/createError.js:16:15)
at settle (.../node_modules/axios/lib/core/settle.js:17:12)
at XMLHttpRequestOverride.onloadend (.../node_modules/axios/lib/ad
... super long logging ...
Such non blocking issue is tackled in other projects using jest as the custom queryClient logger does the job; it seems that it behaves differently using vitest. Does anyone knows which part is the culprit in that context ? What should be done ?
passing a custom logger to the QueryClient is a feature that was introduced in v4.
For v3, you need to call setLogger, which is exported from react-query:
https://react-query-v3.tanstack.com/reference/setLogger
import { setLogger } from 'react-query'
setLogger({
log: console.log,
warn: console.warn,
error: () => {}
})

protractor config file is not picking up the cucumber step definitions

i am new to protractor and cucumber framework. i followed the steps from protractor site and here https://semaphoreci.com/community/tutorials/getting-started-with-protractor-and-cucumber. i have a config file configured with cucumber framework options, feature file and step definition file. But when i run my cucumber-config file it does not recognize my step definitions and always throw an error. any help on this? below are my setup files.
//cucumber-config.js
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
browserName:'chrome'
},
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
specs: [
'./features/*.feature'
],
cucumberOpts: {
require: ['./features/step_definitions/*.steps.js'],
tags: [],
strict: true,
format: ["pretty"],
dryRun: false,
compiler: []
},
onPrepare: function () {
browser.manage().window().maximize();
}
};
//testone.feature
#features/test.feature
Feature: Running Cucumber with Protractor
Scenario: Protractor and Cucumber Test
Given I go to "https://angularjs.org/"
When I add "Be Awesome" in the task field
And I click the add button
Then I should see my new task in the list
//testone_steps.js
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
module.exports = function() {
this.Given(/^I go to "([^"]*)"$/, function(site) {
browser.get(site);
});
this.When(/^I add "([^"]*)" in the task field$/, function(task) {
element(by.model('todoList.todoText')).sendKeys(task);
});
this.When(/^I click the add button$/, function() {
var el = element(by.css('[value="add"]'));
el.click();
});
this.Then(/^I should see my new task in the list$/, function(callback) {
var todoList = element.all(by.repeater('todo in todoList.todos'));
expect(todoList.count()).to.eventually.equal(3);
expect(todoList.get(2).getText()).to.eventually.equal('Do not Be Awesome')
.and.notify(callback);
});
};
when in run protractor cucumber-conf.js, i get the below error...
/opt/protractor_tests
➔ protractor cucumber.config.js
(node:3963) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[21:19:17] I/launcher - Running 1 instances of WebDriver
[21:19:17] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
Feature: Running Cucumber with Protractor
Scenario: Protractor and Cucumber Test
? Given I go to "https://angularjs.org/"
? When I add "Be Awesome" in the task field
? And I click the add button
? Then I should see my new task in the list
Warnings:
1) Scenario: Protractor and Cucumber Test - features/testone.feature:4
Step: Given I go to "https://angularjs.org/" - features/testone.feature:5
Message:
Undefined. Implement with the following snippet:
Given('I go to {stringInDoubleQuotes}', function (stringInDoubleQuotes, callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
2) Scenario: Protractor and Cucumber Test - features/testone.feature:4
Step: When I add "Be Awesome" in the task field - features/testone.feature:6
Message:
Undefined. Implement with the following snippet:
When('I add {stringInDoubleQuotes} in the task field', function (stringInDoubleQuotes, callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
3) Scenario: Protractor and Cucumber Test - features/testone.feature:4
Step: And I click the add button - features/testone.feature:7
Message:
Undefined. Implement with the following snippet:
When('I click the add button', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
4) Scenario: Protractor and Cucumber Test - features/testone.feature:4
Step: Then I should see my new task in the list - features/testone.feature:8
Message:
Undefined. Implement with the following snippet:
Then('I should see my new task in the list', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
1 scenario (1 undefined)
4 steps (4 undefined)
0m00.000s
[21:19:22] I/launcher - 0 instance(s) of WebDriver still running
[21:19:22] I/launcher - chrome #01 failed 1 test(s)
[21:19:22] I/launcher - overall: 1 failed spec(s)
[21:19:22] E/launcher - Process exited with error code 1
/opt/protractor_tests
➔
Updated With Execution error
[15:22:59] I/launcher - Running 1 instances of WebDriver
[15:22:59] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
Feature: Running Cucumber with Protractor
Scenario: Protractor and Cucumber Test
√ Given I go to "https://angularjs.org/"
√ When I add "Be Awesome" in the task field
√ And I click the add button
× Then I should see my new task in the list
Failures:
1) Scenario: Protractor and Cucumber Test - features\testone.feature:4
Step: Then I should see my new task in the list - features\testone.feature:8
Step Definition: features\step_definitions\testone.steps.js:22
Message:
Error: function timed out after 5000 milliseconds
at Timeout.<anonymous> (<local>\ProtractorTests\node_modules\cucumber\lib\user_code_runner.js:91:22)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
1 scenario (1 failed)
4 steps (1 failed, 3 passed)
0m05.049s
[15:23:19] I/launcher - 0 instance(s) of WebDriver still running
[15:23:19] I/launcher - chrome #01 failed 1 test(s)
[15:23:19] I/launcher - overall: 1 failed spec(s)
[15:23:19] E/launcher - Process exited with error code 1
error Command failed with exit code 1.
It's trying to use CucumberJS 2.0.0+ syntax - which is in development at the moment.
Either downgrade CucumberJS to 1.3.1 or below, or do this to your step definitions:
var chai = require('chai'),
expect = chai.expect,
chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var {defineSupportCode} = require('cucumber');
defineSupportCode(({Given, When, Then}) => {
Given(/^I go to "([^"]*)"$/, function(site) {
return browser.get(site);
});
When(/^I add "([^"]*)" in the task field$/, function(task) {
return element(by.model('todoList.todoText')).sendKeys(task);
});
When(/^I click the add button$/, function() {
var el = element(by.css('[value="add"]'));
return el.click();
});
Then(/^I should see my new task in the list$/, function() {
var todoList = element.all(by.repeater('todo in todoList.todos'));
expect(todoList.count()).to.eventually.equal(3);
return expect(todoList.get(2).getText()).to.eventually.equal('Do not Be Awesome');
});
});
Which is the CucumberJS 2.0.0+ syntax
Edit
There are two ways of setting timeouts in CucumberJS 2.0.0
Default timeout
This is to set the default timeout for all of the scenarios that you have:
let scenarioTimeout = 200 * 1000,
{defineSupportCode} = require('cucumber');
defineSupportCode(({setDefaultTimeout}) => {
setDefaultTimeout(scenarioTimeout);
});
In this example, I am setting the scenario timeout to 200 seconds. You can change this to whatever you feel is appropriate.
Individual Steps
This is to set the timeout for a slow step:
When(/^I click the add button$/, {timeout: 60 * 1000}, function() {
var el = element(by.css('[value="add"]'));
return el.click();
});
In this example, the timeout is set to 60 seconds, you may want this larger or smaller, depending on what the step is doing.
In your config file:
require: ['./features/step_definitions/*.steps.js'],
But your file is: testone_steps.js, it should be: testone.steps.js
D'you see the difference? Just change _ to ., because in your config file you are using .

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!

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.