Testing a Controller using Jasmine in Karma - unit-testing

I'm trying to test a controller but I'm getting an error
TypeError: Object # has no method 'apply' ReferenceError:
inject is not defined
The unit-test.js is
define(['angular',
'myApp',
'angularMocks',
'MyCtrl'
], function() {
describe('Testing controller', function() {
var $scope = null;
var ctrl = null;
beforeEach(angular.module('myApp'));
beforeEach(inject(function ($injector) {
$scope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
}));
describe('MyCtrl', function () {
it('should call test variable', function () {
$scope = $rootScope.$new();
ctrl = $controller('MyCtrl', {
$scope: $scope
});
expect($scope.test).toBe("sth");
});
});
});
});
in MyCtrl I have declared a $scope.test = "sth";
When I change
beforeEach(angular.module('myApp')); to beforeEach(module('myApp'));
I'm getting ReferenceError: module is not defined
I use Karma version: 0.9.8 and AngularJS v1.0.8
Thank you very much!

You have a lot of things to do if you're using requirejs.
First you have to put the karma-requirejs plugin in your package.json
"karma-requirejs": "~0.1.0",
Then you have ti change your config file. You have to add requirejs in frameworks part
Then exclude your require main.js
Then add all your librairies files via the pattern config and not include it
You have to add your require main-test.js (config file for test describe at bottom)
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'app/bower_components/jquery/jquery.min.js', included: false},
{pattern: 'app/bower_components/angular/angular.min.js', included: false},
{pattern: 'app/bower_components/angular-resource/angular-resource.min.js', included: false},
{pattern: 'app/bower_components/angular-mocks/angular-mocks.js', included: false},
{pattern: 'app/scripts/*.js', included: false},
{pattern: 'app/scripts/**/*.js', included: false},
{pattern: 'test/spec/**/*Spec.js', included: false},
'test/main-test.js'
],
exclude: ['app/scripts/main.js'],
port: 8082,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false
});
};
Now create your main-test.js.
In you have to get all your tests files to put it as dependencies.
Then do a classic requirejs config (note in the baseUrl we use /base a karma constant) and finally start karma by code through : window.__karma__.start();
Example :
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
}
require.config({
// Karma serves files from '/base'
baseUrl: '/base/app/scripts',
paths: {
jquery: '../bower_components/jquery/jquery.min',
angular: '../bower_components/angular/angular.min',
angularMocks: '../bower_components/angular-mocks/angular-mocks',
ngResource: '../bower_components/angular-resource/angular-resource.min'
},
shim: {
jquery: {
exports: '$'
},
angular: {
deps: [ 'jquery', 'bootstrap'],
exports: 'angular'
},
ngResource: {
deps: [ 'angular' ],
exports: 'ngResource'
},
angularMocks: {
deps: [ 'ngResource' ],
exports: 'angularMocks'
}
},
priority: [
'angular'
],
// ask Require.js to load these files (all our tests)
deps: tests
});
require(tests, function(){
window.__karma__.start();
});
In your test file :
change beforeEach(angular.module('myApp')); to beforeEach(module('myApp'));
Change the params of your define like that :
define(['angular',
'myApp',
'angularMocks',
'MyCtrl'
], function(angular, myApp, angularMocks, MyCtrl)
To inject controller just do that (You have to put the MyCtrl in param of your require function) :
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
$controller(MyCtrl, {
$scope: scope
});
}));
And finally :
it('should call crudListMethods', function () {
expect(scope.test).toBe("sth");
});
Now it should work ! Hope it helps !

Related

Karma isn't suffixing the file with .js in angular 2 unit tests

i followed the instructions in quickstart and https://angular.io/docs/ts/latest/guide/testing.html but
Karma cannot load angular 2 component. getting this error,
404: /base/assets/components/app/myapp.component
file structure:
assets
| |components
| | |app
| | | |myapp.component.ts
| | | |myapp.component.spec.ts
| |systemjs.config.js
|karma.conf.js
|karma-test-shim.js
systemjs.config.js:
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
myngapp: 'components/app',
myapp: 'components/app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
'#angular/upgrade': 'npm:#angular/upgrade/bundles/upgrade.umd.js',
'#angular/upgrade/static': 'npm:#angular/upgrade/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'typescript': 'npm:typescript/lib/typescript.js'
},
transpiler: 'typescript',
typescriptOptions: {
emitDecoratorMetadata: true
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
myngapp: {
main: './main.ts',
defaultExtension: 'ts'
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
karma.conf.js:
module.exports = function(config) {
var appBase = 'assets/components/'; // transpiled app JS and map files
var appSrcBase = 'assets/components/'; // app source TS files
var appAssets = 'base/assets/components/app'; // component assets fetched by Angular's compiler
// Testing helpers (optional) are conventionally in a folder called `testing`
var testingBase = 'assets/components/'; // transpiled test JS and map files
var testingSrcBase = 'assets/components/'; // test source TS files
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter')
],
client: {
builtPaths: [appBase, testingBase], // add more spec base paths as needed
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
customLaunchers: {
// From the CLI. Not used here but interesting
// chrome setup for travis CI using chromium
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
files: [
// System.js for module loading
'node_modules/systemjs/dist/system.src.js',
// Polyfills
'node_modules/core-js/client/shim.js',
// zone.js
'node_modules/zone.js/dist/zone.js',
// 'assets/components/systemjs.config.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/zone.js/dist/proxy.js',
'node_modules/zone.js/dist/sync-test.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/zone.js/dist/async-test.js',
'node_modules/zone.js/dist/fake-async-test.js',
// RxJs
// 'assets/components/systemjs.config.js',
{ pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false },
// Paths loaded via module imports:
// Angular itself
//'node_modules/#angular/**/*.js',
{ pattern: 'node_modules/#angular/**/*.js', included: false, watched: false },
{ pattern: 'node_modules/#angular/**/*.js.map', included: false, watched: false },
//'assets/components/systemjs.config.js',
{ pattern: 'assets/components/systemjs.config.js', included: false, watched: false },
'karma-test-shim.js',
// transpiled application & spec code paths loaded via module imports
{ pattern: appBase + '**/*.js', included: false, watched: true },
{ pattern: testingBase + '**/*.js', included: false, watched: true },
// Asset (HTML & CSS) paths loaded via Angular's component compiler
// (these paths need to be rewritten, see proxies section)
{ pattern: appBase + '**/*.html', included: false, watched: true },
{ pattern: appBase + '**/*.css', included: false, watched: true },
// Paths for debugging with source maps in dev tools
{ pattern: appSrcBase + '**/*.ts', included: false, watched: true },
{ pattern: appBase + '**/*.js.map', included: false, watched: false },
{ pattern: testingSrcBase + '**/*.ts', included: false, watched: true },
{ pattern: testingBase + '**/*.js.map', included: false, watched: false}
],
// Proxied base paths for loading assets
proxies: {
// required for component assets fetched by Angular's compiler
"/app/": appAssets
},
exclude: [],
preprocessors: {},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
karma-test-shim.js:
// /*global jasmine, __karma__, window*/
Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.
// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
// builtPaths: root paths for output ("built") files
// get from karma.config.js, then prefix with '/base/' (default is 'app/')
var builtPaths = (__karma__.config.builtPaths || ['assets/components/app/'])
.map(function(p) { return '/base/'+p;});
__karma__.loaded = function () { };
function isJsFile(path) {
return path.slice(-3) == '.js';
}
function isSpecFile(path) {
return /\.spec\.(.*\.)?js$/.test(path);
}
// Is a "built" file if is JavaScript file in one of the "built" folders
function isBuiltFile(path) {
return isJsFile(path) &&
builtPaths.reduce(function(keep, bp) {
return keep || (path.substr(0, bp.length) === bp);
}, false);
}
var allSpecFiles = Object.keys(window.__karma__.files)
.filter(isSpecFile)
.filter(isBuiltFile);
System.config({
baseURL: 'base',
// Extend usual application package list with test folder
packages: {
'testing': { main: 'main.js', defaultExtension: 'js' }
},
// Assume npm: is set in `paths` in systemjs.config
// Map the angular testing umd bundles
map: {
'#angular/core/testing': 'npm:#angular/core/bundles/core-testing.umd.js',
'#angular/common/testing': '.npm:#angular/common/bundles/common-testing.umd.js',
'#angular/compiler/testing': 'npm:#angular/compiler/bundles/compiler-testing.umd.js',
'#angular/platform-browser/testing': 'npm:#angular/platform-browser/bundles/platform-browser-testing.umd.js',
'#angular/platform-browser-dynamic/testing': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
'#angular/http/testing': 'npm:#angular/http/bundles/http-testing.umd.js',
'#angular/router/testing': 'npm:#angular/router/bundles/router-testing.umd.js',
'#angular/forms/testing': 'npm:#angular/forms/bundles/forms-testing.umd.js',
},
});
System.import('assets/components/systemjs.config.js')
.then(initTestBed)
.then(initTesting);
/** Optional SystemJS configuration extras. Keep going w/o it */
/*function importSystemJsExtras(){
return System.import('systemjs.config.extras.js')
.catch(function(reason) {
console.log(
'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.'
);
console.log(reason);
});
}*/
//initTestBed();
//initTesting();
function initTestBed(){
return Promise.all([
System.import('#angular/core/testing'),
System.import('#angular/platform-browser-dynamic/testing')
])
.then(function (providers) {
var coreTesting = providers[0];
var browserTesting = providers[1];
coreTesting.TestBed.initTestEnvironment(
browserTesting.BrowserDynamicTestingModule,
browserTesting.platformBrowserDynamicTesting());
})
}
// Import all spec files and start karma
function initTesting () {
return Promise.all(
allSpecFiles.map(function (moduleName) {
return System.import(moduleName);
})
)
.then(__karma__.start, __karma__.error);
}
If i go to the compile js file of my test (myapp.component.spec.js) and change the import from myapp.component to myapp.component.js, test runs successfully. given example below,
eg:
when compiled by angular myapp.component.spec.js looks like,
var myapp_component_1 = require('./myapp.component');
i update it to
var myapp_component_1 = require('./myapp.component.js');
and test runs
i do not know why it cannot find the component even though the path is correct. Please help.

How to write a jasmine unit test for my angular2 forms that uses parsley validation?

I am trying to use Parsley validation for an angular2 app I am writing and wants to write some jasmine unit tests. I want to make sure that the input gets validated in the correct way.
I am trying to write a small test, but I think the problem I have is that I can't parsley to load. I'm running a karma runner and have tried to include it in the config files for that.
This is my test file:
///<reference path="./../../../../typings/globals/jasmine/index.d.ts"/>
import { Component, DebugElement, AfterViewInit } from "#angular/core";
import { By } from "#angular/platform-browser";
import { ComponentFixture, TestBed, async } from "#angular/core/testing";
import { FormsModule } from '#angular/forms';
import { ComponentFixtureAutoDetect } from '#angular/core/testing';
import { dispatchEvent } from '#angular/platform-browser/testing/browser-util';
declare var jQuery: any;
describe("StringLengthValidationApp", () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ FormsModule ],
declarations: [StringLengthValidationApp],
providers: [
{ provide: ComponentFixtureAutoDetect, useValue: true }
]
});
});
beforeEach(async(() => {
TestBed.compileComponents();
}));
it("should work", () => {
let fixture = TestBed.createComponent(StringLengthValidationApp);
fixture.detectChanges();
return fixture.whenStable().then(() => {
const inputName = 'quick BROWN fox';
let nameInput = fixture.debugElement.query(By.css('input')).nativeElement;
nameInput.value = inputName;
nameInput.dispatchEvent(new Event('input'));
fixture.detectChanges();
let second = fixture.debugElement.query(By.css('textarea')).nativeElement;
second.value = inputName;
second.dispatchEvent(new Event('input'));
fixture.detectChanges();
console.log(fixture.nativeElement);
let errors = fixture.debugElement.queryAll(By.css("ul"));
expect(errors.length).toBe(1);
});
});
});
#Component({
selector: "date-validation-app",
template: `
<form id="form"
class="form-horizontal form-label-left parsleyjs"
data-parsley-validate=""
data-parsley-priority-enabled="false"
novalidate="novalidate">
<input type="text" id="basic" name="basic" class="form-control"
required="required"
data-parsley-trigger="change"
data-parsley-maxlength="3" />
<textarea name="textarea" rows="10" cols="50">Write something here</textarea>
</form>
`
})
class StringLengthValidationApp {
}
My karma.conf.js
var webpackConfig = require('./webpack.test');
module.exports = function (config) {
var _config = {
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: './config/karma-test-shim.js', watched: false }
],
preprocessors: {
'./config/karma-test-shim.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
webpackServer: {
noInfo: true
},
reporters: ['kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false
};
config.set(_config);
};
And karma-test-shim.js
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('core-js/es7/reflect');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
require('jquery/src/jquery');
require('parsleyjs/dist/parsley.js');
var appContext = require.context('../src', true, /\.spec\.ts/);
appContext.keys().forEach(appContext);
var testing = require('#angular/core/testing');
var browser = require('#angular/platform-browser-dynamic/testing');
testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
I get an error message like this
Uncaught Error: Error in :0:0 caused by: form.parsley is not a function
TypeError: form.parsley is not a function
When not running with the ngAfterViewInit function trying to bind parsley, it will run but I get the test failing with
Error: Expected 0 to be 1.
And when looking at it in Chrome no validation error is visible either.
My suspicion is that parsley isn't initiated, but I am new to this so I guess I can have made any simple mistake or that it can be anything else that is wrong
Any hints on what do to solve it will be very appreciated
I think I solved the problem by simply adding
'node_modules/parsleyjs/dist/parsley.js',
to the files section in my karma.conf.js

Angular2 Unit Test with Karma and Jasmin

I'm struggling getting my Angular2 Unit Tests up and running.
I'm guessing it has something to do with my module loading.
This is the error I'm getting:
WARN [web-server]: 404:
/base/public/dev/assets/lib/node_modules/angular2/src/platform/browser/browser_adapter.js
Missing error handler on socket.
TypeError: (msg || "").replace is not a function
This is my karma.config.js
module.exports = function(config) {
config.set({
basePath: ".",
frameworks: ["jasmine"],
files: [
// paths loaded by Karma
{ pattern: "public/dev/assets/lib/node_modules/angular2/bundles/angular2-polyfills.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/systemjs/dist/system.src.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/rxjs/bundles/Rx.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/angular2/bundles/angular2.dev.js", included: true, watched: true },
{ pattern: "public/dev/assets/lib/node_modules/angular2/bundles/testing.dev.js", included: true, watched: true },
{ pattern: "karma-test-shim.js", included: true, watched: true },
// paths loaded via module imports
{ pattern: "public/dev/assets/scripts/app/**/*.js", included: false, watched: true },
// paths to support debugging with source maps in dev tools
{ pattern: "public/dev/assets/scripts/app/**/*.ts", included: false, watched: false },
{ pattern: "public/dev/assets/scripts/app/**/*.js.map", included: false, watched: false }
],
// proxied base paths
proxies: {
// required for component assests fetched by Angular"s compiler
// Redirect all "/public/" paths to "/base/public" (Karma serves files from /base/)
"/public/": "/base/public/"
},
port: 9876,
logLevel: config.LOG_INFO,
colors: true,
autoWatch: true,
browsers: ["Chrome"],
// Karma plugins loaded
plugins: [
"karma-jasmine",
"karma-coverage",
"karma-chrome-launcher"
],
// Coverage reporter generates the coverage
reporters: ["progress", "dots", "coverage"],
// Source files that you wanna generate coverage for.
// Do not include tests or libraries (these files will be instrumented by Istanbul)
preprocessors: {
"public/dev/assets/scrips/app/**/!(*spec).js": ["coverage"]
},
coverageReporter: {
reporters:[
{type: "json", subdir: ".", file: "coverage-final.json"}
]
},
singleRun: true
})
};
This is my karma-test-shim.js
// Tun on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;
// // Cancel Karma's synchronous start,
// // we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.config({
defaultJSExtensions: true,
map: {
angular2: "public/dev/assets/lib/node_modules/angular2",
rxjs: "public/dev/assets/lib/node_modules/rxjs"
},
packages: {
'base/public': {
format: 'register',
map: Object.keys(window.__karma__.files)
.filter(onlyAppFiles)
.reduce(createPathRecords, {})
}
}
});
System.import('angular2/src/platform/browser/browser_adapter')
.then(function(browser_adapter) { browser_adapter.BrowserDomAdapter.makeCurrent(); })
.then(function() { return Promise.all(resolveTestFiles()); })
.then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); });
function createPathRecords(pathsMapping, appPath) {
// creates local module name mapping to global path with karma's fingerprint in path, e.g.:
// './vg-player/vg-player':
// '/base/dist/vg-player/vg-player.js?f4523daf879cfb7310ef6242682ccf10b2041b3e'
var pathParts = appPath.split('/');
var moduleName = './' + pathParts.slice(Math.max(pathParts.length - 2, 1)).join('/');
moduleName = moduleName.replace(/\.js$/, '');
pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath];
return pathsMapping;
}
function onlyAppFiles(filePath) {
return /\/base\/public\/dev\/assets\/(?!.*\.spec\.js$).*\.js$/.test(filePath);
}
function onlySpecFiles(path) {
return /\.spec\.js$/.test(path);
}
function resolveTestFiles() {
return Object.keys(window.__karma__.files) // All files served by Karma.
.filter(onlySpecFiles)
.map(function(moduleName) {
// loads all spec files via their global module names (e.g.
// 'base/dist/vg-player/vg-player.spec')
return System.import(moduleName);
});
}
As you can see I'm redirecting all /public/ paths to /base/public/ to handle the Karma default /base/ serving of files.
I double checked the path of the file that throws the 404, and it exists in the path provided (minus the /base/).
Can anyone point me in the right direction as to what may be going wrong here?
Thx!

Module not found: Error: Cannot resolve 'file' or 'directory'

Can you guys please help me fixing this issue.
I have two .jsx files one imported under another one.
Lets say,
A.jsx(Inside A.jsx I have imported the B.jsx)
B.jsx
When both the files are written under same file in that case unit test cases working fine. The moment I am separating it out, still the component is working fine but the unit test cases are not running. Webpack karma throwing an error saying
ERROR in ./src/components/thpfooter/index.jsx Module not found: Error: Cannot resolve 'file' or 'directory' ./ThpFooterList in /Users/zi02/projects/creps_ui_components_library/src/components/thpfooter # ./src/components/thpfooter/index.jsx 9:1725-1751
karma.conf.js
/*eslint-disable*/
var webpack = require('karma-webpack');
var argv = require('yargs').argv;
var componentName = "**";
if (typeof argv.comp !== 'undefined' && argv.comp !== null && argv.comp !== "" && argv.comp !== true) {
componentName = argv.comp;
}
var testFiles = 'src/components/'+componentName+'/test/*.js';
var mockFiles = 'src/components/'+componentName+'/test/mock/*.json';
module.exports = function (config) {
config.set({
frameworks: ['jasmine'],
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
testFiles,
mockFiles
],
plugins: [webpack,
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-coverage',
'karma-spec-reporter',
'karma-json-fixtures-preprocessor',
'karma-junit-reporter'],
browsers: ['PhantomJS'],
preprocessors: {
'src/components/**/test/*.js': ['webpack'],
'src/components/**/*.jsx': ['webpack'],
'src/components/**/test/mock/*.json': ['json_fixtures']
},
jsonFixturesPreprocessor: {
// strip this from the file path \ fixture name
stripPrefix: 'src/components/',
// strip this to the file path \ fixture name
prependPrefix: '',
// change the global fixtures variable name
variableName: '__mocks__',
// camelize fixture filenames
// (e.g 'fixtures/aa-bb_cc.json' becames __fixtures__['fixtures/aaBbCc'])
camelizeFilenames: true,
// transform the filename
transformPath: function (path) {
return path + '.js';
}
},
reporters: ['spec', 'coverage','junit'],
coverageReporter: {
dir: 'build/reports/coverage',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
},
junitReporter: {
outputDir: 'build/reports/coverage/junit/'+componentName,
suite: ''
},
webpack: {
module: {
loaders: [{
test: /\.(js|jsx)$/, exclude: /node_modules/,
loader: 'babel-loader'
}],
postLoaders: [{
test: /\.(js|jsx)$/, exclude: /(node_modules|test)/,
loader: 'istanbul-instrumenter'
}]
}
},
webpackMiddleware: { noInfo: true }
});
};
footer.jsx
import React from 'react';
import ThpFooterList from './ThpFooterList';
class ThpFooter extends React.Component {
//footer code here
}
ThpFooterList.jsx
import React from 'react';
class ThpFooterList extends React.Component {
//footer list code here
}
See above component is working but I am not able to execute the unit test case. When you keep both of them in one file means footer and footerlist.jsx then component as well as the unit test cases are executing.
unit test case file
/* eslint-env jasmine */
import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils';
import ThpFooter from '../index.jsx';
describe('ThpFooter', () => {
let component;
let content;
let shallowRenderer;
let componentShallow;
beforeAll(() => {
content = window.__mocks__['thpfooter/test/mock/content'];
component = TestUtils.renderIntoDocument(<ThpFooter data={content}/>);
shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<ThpFooter data={content}/>);
componentShallow = shallowRenderer.getRenderOutput();
});
describe('into DOM', () => {
it('Should be rendered into DOM', () => {
expect(component).toBeTruthy();
});
it('Should have classname as footer-container', () => {
const classname = TestUtils.scryRenderedDOMComponentsWithClass(component, 'footer-container');
expect(classname[0].className).toBe('footer-container');
});
it('Should have className as footer-wrapper', () => {
const classname = TestUtils.scryRenderedDOMComponentsWithClass(component, 'footer-wrapper');
expect(classname[0].className).toBe('footer-wrapper');
});
});
describe('into shallow renderer', () => {
it('Should be rendered as shallow renderer', () => {
expect(componentShallow).toBeTruthy();
});
it('Should have classname as footer-container', () => {
expect(componentShallow.props.className).toBe('footer-container');
});
it('Should have className as footer-wrapper', () => {
expect(componentShallow.props.children.props.children[0].props.className).toBe('footer-wrapper');
});
});
});
I experienced the same error on one of the development machines. Although gulp and webpack-stream was used in my case, I think you may reference my method to try solving it.
On my mac, everything is fine but when I pushed the code to the ubuntu development platform, this problem was observed. After some googling I cannot solve it but then I tried to make the file path to be shorter and then suddenly it works on the ubuntu development platform too! You may try to shorten the file name or place it in a shorter path and test to see if it works.
Watch for case sensitivity. Mac file system is not case-sensitive, windows/linux is.

ReferenceError: Can't find variable: module or inject running unit-tests in test.js file

I'm getting an error in my terminal output from PhantomJS ReferenceError: Can't find variable: module in www/signin/tests/signin.service.tests.js and ReferenceError: Can't find variable: inject in www/signin/tests/signin.service.tests.js where they are called in the code below.
describe('signinService', function(){
var controller,
deferredSigin,
signinServiceMock,
stateMock,
hasClass = function (element, cls) {
return element.getAttribute('class').then(function (classes) {
return classes.split(' ').indexOf(cls) !== -1;
});
};
beforeEach(function(){
module('app');
});
// disable template caching
beforeEach(module(function($provide, $urlRouterProvider) {
$provide.value('$ionicTemplateCache', function(){} );
$urlRouterProvider.deferIntercept();
}));
beforeEach(inject(function($controller, $q){
deferredSigin = $q.defer();
signinServiceMock = {
signin: jasmine.createSpy('signin spy').and.returnValue(deferredSigin.promise)
};
stateMock = jasmine.creatSpyObj('$state spy', ['go']);
controller = $controller('SiginController', {
'$state': stateMock,
'signinService': signinServiceMock
});
}));
I have my unit-test.conf.js in the root of my application with file paths configured as shown
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'www/lib/angular/angular.min.js',
'www/lib/angular-mocks/angular-mocks.js',
'www/app.js',
'www/signin/services/*.js',
'www/signin/*.js',
'www/signin/tests/*.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
});
};
I was following this tutorial. It seems like angular-mocks isn't getting loaded. Not sure why. I'm passing it in the files in unit-test.conf.js