Currently, I am working on an Angular application that has multiple test files sharing the same mocks. I am looking for a way to extract these mocks and store them in a separate file.
Initially, I attempted to create an object and reuse it in my tests, but encountered an exception: ReferenceError: Can't find variable: require
Below is my Karma file configuration:
// Karma file configuration
module.exports = {
options: {
frameworks: ['jasmine'],
preprocessors: {
'<%= paths.scripts %>/**/*.js': ['coverage']
},
reporters: ['progress', 'coverage', 'junit'],
coverageReporter: {
dir : '<%= paths.coverage %>',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'cobertura', subdir: '.', file: 'code-coverage.xml' },
]
},
junitReporter: {
outputFile: '<%= paths.testReport %>/test-results-karma.xml'
},
port: 9999,
colors: true,
logLevel: 'INFO',
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: true
},
portal: {
// Additional configuration for portal
options: {
basePath: 'public/',
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'bower_components/angular-translate/angular-translate.js',
'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'scripts/<%= paths.module %>',
'scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/unit/**/*.js'
]
}
}
};
Here is the mock code snippet:
var EcMock = (function() {
'use strict';
function ecMock() {
this.dom = {
addClass: function() {
return angular.noop();
},
getViewportWidth: function() {
return angular.noop();
}
};
this.detect = {
geolocation: true
};
}
return ecMock;
})();
module.exports = EcMock;
Usage of the mock in Karma test file:
var EcMock = require('../../../../mock/EcMock');