I have as simple "hello world" project and I want to test the famous hélloWorld function.
The project is structured like this:
├── package.json
├── spec
│ ├── helloWorldSpec.js
│ └── support
│ └── jasmine.json
└── src
└── helloWorld.js
And the file content:
package.json
{
"name": "jasmineTest",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "BSD-2-Clause",
"dependencies": {
"jasmine": "~2.1.0"
}
}
spec/helloWorldSpec.js
// var helloWorld = require('../src/helloWorld.js');
describe('Test', function() {
it('it', function() {
helloWorld();
});
});
src/helloWorld.js
function helloWorld() {
return "Hello world!";
}
// module.exports = helloWorld;
spec/support/jasmine.json
{
"spec_dir": "spec",
"spec_files": [
"**/*[sS]pec.js"
],
"helpers": [
"helpers/**/*.js"
]
}
My problem:
When I run npm install
jasmine is downloaded.
=> ok
When I run ./node_modules/jasmine/bin/jasmine.js
I have the error ReferenceError: helloWorld is not defined ReferenceError: helloWorld is not defined
My Question:
How can I access the method helloWord contained in src/helloWorld.js
in the test scope without using module.exports = xxx.
A solution is to use Grunt.
Create a GruntFile.js containing:
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jasmine: {
src: ['src/**/*.js'],
options: {
specs: ['spec/**/*Spec.js'],
vendor: []
}
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
};
Update package.json with grunt, grunt-cli and grunt-contrib-jasmine dependencies
{
"name": "jasmineTest",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "BSD-2-Clause",
"dependencies": {
"jasmine": "~2.1.0",
"grunt": "~0.4.5",
"grunt-cli": "~0.1.13",
"grunt-contrib-jasmine": "~0.8.1"
}
}
Update npm dependencies:
npm update
And relaunch test using grunt and not directly jasmine:
./node_modules/grunt-cli/bin/grunt jasmine
And you got:
Running "jasmine:src" (jasmine) task
Testing jasmine specs via PhantomJS
Test
- it...
log: Spec 'Test it' has no expectations.
✓ it
1 spec in 0.008s.
>> 0 failures
Done, without errors.
According to Jasmine staff :
You don't need to specify your source files in the config - just require them in from your spec files.
https://github.com/jasmine/jasmine-npm/issues/49
But then, you do need to use export. This is not a Jasmine issue but vanilla Javascript. You want to call a method from another file so you need to export and require it. Why don't you want to ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With