I'm trying to do UI testing with jasmine-jquery. I'm using karma as my test runner and jasmine as my testing framework. I think I've loaded the fixture successfully and jasmine-jquery is listed as a testing framework inside my karma configuration.
However I'm unable to find an element in the DOM using jasmine-jquery. Why?
Directory structure
base
spec
javascripts
fixtures
myfixture.html
karma.conf.js
tests
settingUpHTMLFixtures.test.js
myfixture.html
<div id="my-fixture">foo bar</div>
settingUpHTMLFixtures.test.js
jasmine.getFixtures().fixturesPath = 'base/spec/javascripts/fixtures';
loadFixtures('myfixture.html');
describe('testing out jasmine-jquery', function(){
it('can find an element in the dom using jasmine-jquery', function(){
expect($j('#my-fixture')).toBeInDOM();
})
})
karma.conf.js
const webpackConfig = require('./webpack.config.js');
module.exports = function(config) {
config.set({
basePath: "",
files: ["tests/**/*.test.js", 'spec/javascripts/fixtures/*.html'],
frameworks: ['jasmine-jquery', 'jasmine', 'jasmine-matchers'],
preprocessors: {
"tests/**/*.test.js": ["webpack"]
},
webpack: webpackConfig,
plugins : [
'karma-chrome-launcher',
'karma-jasmine',
'karma-jasmine-jquery',
'karma-jasmine-matchers',
'karma-webpack',
'karma-jasmine-html-reporter'
],
logLevel: config.LOG_INFO,
reporters: ['kjhtml'],
port: 9876,
browsers: ["Chrome"],
//...
});
};
At the moment I'm just getting the message that the test failed, which is
testing out jasmine-jquery can find an element in the dom using jasmine-jquery FAILED
Expected jQuery({ context: HTMLNode, selector: '#my-fixture' }) to be in d o m.
at UserContext.<anonymous> (tests/settingUpHTMLFixtures.test.js:78:31)"
I had a path error. It was a mistake to create the base directory on my own. Karma simply serves everything from the base directory.
The only time I needed to use the word base was when setting the fixtures path (as shown in my settingUpHTMLFixtures.test.js code above)
Related
I'm currently trying to get code coverage on my fastify routes using Mocha and NYC.
I've tried instrumenting the code beforehand and then running the tests on the instrumented code as well as just trying to setup NYC in various ways to get it to work right.
Here is my current configuration. All previous ones produced the same code coverage output):
nyc config
"nyc": {
"extends": "#istanbuljs/nyc-config-typescript",
"extension": [
".ts",
".tsx"
],
"exclude": [
"**/*.d.ts",
"**/*.test.ts"
],
"reporter": [
"html",
"text"
],
"sourceMap": true,
"instrument": true
}
Route file:
const routes = async (app: FastifyInstance, options) => {
app.post('/code', async (request: FastifyRequest, response: FastifyReply<ServerResponse>) => {
// route logic in here
});
};
The integration test:
import * as fastify from fastify;
import * as sinon from 'sinon';
import * as chai from 'chai';
const expect = chai.expect;
const sinonChai = require('sinon-chai');
chai.use(sinonChai);
describe('When/code POST is called', () => {
let app;
before(() => {
app = fastify();
// load routes for integration testing
app.register(require('../path/to/code.ts'));
});
after(() => {
app.close();
});
it('then a code is created and returned', async () => {
const {statusCode} = await apiTester.inject({
url: '/code',
method: 'POST',
payload:{ code: 'fake_code' }
});
expect(statusCode).to.equal(201);
});
});
My unit test call looks like the following:
nyc mocha './test/unit/**/*.test.ts' --require ts-node/register --require source-map-support/register --recursive
I literally get 5% code coverage just for the const routes =. I'm really banging my head trying to figure this one out. Any help would be greatly appreciated! None of the other solutions I have investigated on here work.
I have a detailed example for typescript + mocha + nyc. It also contains fastify tests including route tests (inject) as well as mock + stub and spy tests using sinon. All async await as well.
It's using all modern versions and also covers unused files as well as VsCode launch configs. Feel free to check it out here:
https://github.com/Flowkap/typescript-node-template
Specifically I think that
instrumentation: true
messes up the results. Heres my working .nycrc.yml
extends: "#istanbuljs/nyc-config-typescript"
reporter:
- html
- lcovonly
- clover
# those 2 are for commandline outputs
- text
- text-summary
report-dir: coverage
I have proper coverage even for mocked ans tub parts of fastify in my above mentioned example.
I'm having a hell of a time with Karma/Jasmine. I'm just trying to run the example specs from Jasmine's site.
When I run jasmine on command line, the tests run fine. However, if I try to run them using Karma test runner, I have a multitude of problems.
Here's My File Structure
Here's my karma.conf.js file:
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: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'node_modules/requirejs/require.js',
'**/test-main.js', {
pattern: 'spec/jasmine_examples/*.js',
included: false
}
],
// list of files to exclude
exclude: ['**/*conf.js'],
...port,browser etc.
Here's my test.main.js file
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
When I run karma start, I get a 404 that PlayerTest.js and SongTest.js are not under base/. However they are loaded and located in base/spec/jasmine_examples. In addition, PlayerTest.js throws an error "module not defined".
Honestly, what am I doing wrong?
I think you need to refer to the karma-requirejs and the karma-jasmine plugins in the karma.conf.js file -
config.set({
plugins: [
'karma-jasmine',
'karma-requirejs'
],
From karma doc, it states:
Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).
Additional information can be found in plugins.
You will not need to have require.js in the files section.
I really really want to get jasmine-jquery working with jasmine. Not only will it make manipulating the DOM a breeze but it will also provide me with a ton of useful matchers.
However, it gives me this error when I try to start my spec runner:
ReferenceError: Can't find variable: define
at /.../app/vendor/assets/bower_components/jquery/src/jquery.js:37
Any idea what this means? I'm using Karma to run my specs. Here's my unit.js config:
module.exports = function(config) {
config.set({
basePath: '..',
// frameworks to use
frameworks: ['jasmine'],
urlRoot: '/_karma_/',
// list of files / patterns to load in the browser
files: [
'vendor/assets/bower_components/angular/angular.js',
'vendor/assets/bower_components/angular-mocks/angular-mocks.js',
'vendor/assets/bower_components/angular-resource/angular-resource.js',
'vendor/assets/bower_components/angular-cookies/angular-cookies.js',
'vendor/assets/bower_components/angular-sanitize/angular-sanitize.js',
'vendor/assets/bower_components/angular-route/angular-route.js',
'vendor/assets/bower_components/jquery/src/jquery.js', // added this first
'vendor/assets/jasmine-jquery.js', // and then this...
'vendor/assets/bower_components/jasmine-jquery/lib/jasmine-jquery.js',
'app/assets/javascripts/application.js.coffee',
'app/assets/javascripts/**/**',
'spec/javascripts/**/*'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['dots'],
// 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_INFO,
autoWatch: true,
plugins : [
'jasmine-given',
'requirejs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-opera-launcher',
'karma-jasmine',
'karma-ng-scenario',
'karma-phantomjs-launcher',
'karma-coffee-preprocessor'
],
browsers: ['PhantomJS','Chrome','Firefox','Opera'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
// Preprocessors
preprocessors: {
'/**/*.coffee':'coffee',
'**/*.slim': ['slim', 'ng-html2js']
}
/*
ngHtml2JsPreprocessor: {
stripPrefix: 'app/assets/templates/',
stripSufix: '.slim'
}
*/
});
All I've done, per the instructions is download jquery, download jasmine-jquery and then require them in Karma's spec file:
files: [
'vendor/assets/bower_components/jquery/src/jquery.js', // added this first
'vendor/assets/jasmine-jquery.js', // and then this...
]
But jquery keeps giving me that undefined is not defined error.
I get no warnings from karma about the paths being wrong.
So how do I get jasmine-jquery working?
Could requirejs have something to do with getting it working?
As mentioned in the response to this question you need to make sure you npm download jasmine-query.
You'll need to change the following in you karma.conf.js:
frameworks: ['jasmine-jquery', 'jasmine']
I'm totally new to the concept of testing, and i need one solid example on how to do it in my project:
I have a gulp file goes like this (Not all of it, just the important portions)
gulp.task('bundle', function() {
gulp.src('public/angular-app/main.js')
.pipe(browserify({
debug: true
}))
.pipe(gulp.dest('public/min-js'));
});
This is a slight portion of my main.js:
'use strict';
angular.module('myApp', [
'ui.router',
'ui.bootstrap',
'ngSanitize',
'ngFx',
...
], ['$interpolateProvider',
function($interpolateProvider) {
$interpolateProvider.startSymbol('{{');
$interpolateProvider.endSymbol('}}');
}
])
.config(require('./config/routes'))
.config(require('./config/authInterceptor'))
.run(require('./config/runPhase'))
.run(require('./config/xeditable'))
.controller('homeController', require('./controllers/homeController'))
.controller('modalInstanceCtrl', require('./controllers/modalInstanceCtrl'))
.controller('modalparticipantCtrl',require('./controllers/modalParticipantCtrl'))
.controller('generatorController',require('./controllers/generatorController'))
.controller('navController', require('./controllers/navController'))
.controller('signInController', require('./controllers/signInController'))
.controller('pricingController', require('./controllers/pricingController'))
.controller('howItWorksController',require('./controllers/howItWorks'))
...
Now this is my config file for karma:
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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/angular/angular.js',
'public/vendor/angular-mocks/angular-mocks.js',
'public/angular-app/**/*.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
When i run karma with karma start this is what i get:
Uncaught reference error:require is not defined
at root/public/angular-app/main.js
So my question is simple, how can i do tests, for example, on my homeController...
//update
So I updated my test file to this:
describe("An Angularjs test suite",function(){
var target, rootScope;
beforeEach(inject(function($rootScope) {
rootScope = $rootScope;
// Mock everything here
spyOn(rootScope, "$on")
}));
beforeEach(inject(function(homeController) {
target = homeController;
}));
it('should have called rootScope.$on', function(){
expect(rootScope.$on).toHaveBeenCalled();
});
});
and my config file to this:
// list of files / patterns to load in the browser
files: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/angular/angular.js',
'public/vendor/angular-mocks/angular-mocks.js',
'public/min-js/main.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
browserify: {
watch: true,
debug: true
},
preprocessors: {
'test/*': ['browserify']
},
Still nothing works, first he says 'unknown provider homeControllerProvider',
Now if i delete them lines:
beforeEach(inject(function(homeController) {
target = homeController;
}));
it still gives me error, expected spy $on to be called, How do i fix this?
You need to inform Karma to run Browserify before running tests.
You can add this in your Karma config:
{
browserify: {
watch: true,
debug: true
},
preprocessors: {
'test/*': ['browserify']
}
}
Karma config file reference: http://karma-runner.github.io/0.12/config/configuration-file.html
Or have a look at one of of my projects that uses Karma for testing: smild.
I'm trying to run Karma with the TeamCity reporter. But when I run the test suite, it fails with:
Error: No provider for "framework:qunit"! (Resolving: framework:qunit)
This works fine when the output is set to 'progress', but not when I add 'teamcity'.
My karma config looks as follows:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['qunit'],
files: [
'scripts/nml/marco/tests/tempTest.js'
],
exclude: [
],
reporters: ['progress', 'teamcity'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
captureTimeout: 60000,
singleRun: true
});
};
My test is still very simple:
(function () {
test('Test one equals one', function () {
equal(1, 1);
});
})();
Any ideas?
I figured out my problem. When I installed the TeamCity reporter, I did it to my current folder instead of the global karma folder. So I think the runner got confused with only a small set of files being in the current folder (and that overrode the global settings).
I was wrong, the tests did not pass any more when just running with the 'progress' reporter.