Jasmine testing with external javascript - javascript

Well I am trying to fire up my first Jasmine test with Karma. I want to test my main javascript file declared functions, but I'm stuck on it... In my specRunner.html I included every files which needed, in karma.conf.js I added both my test specification and main js files also files: ['src/scripts/main.js','src/tests/mySpec.js'].
In my main.js there is the function I want to use
function testFunctionOne(a, b) {
return a * b;
}
So in mySpec.js file there is the test:
describe('testFunctionOne function', function () {
it('should return a * b', function () {
expect(testFunctionOne(2,4).toEqual(8));
});
});
My question is what am I forgot? What am I making wrong? Keep in mind, this is my first attempt for Jasmine testing.

expect(testFunctionOne(2,4)).toEqual(8); not expect(testFunctionOne(2,4).toEqual(8)); I think

Related

How to generate unit tests from a JS module automatically?

I have inherited a project with multiple JavaScript files. Each of them has a bunch of functions; the files are defined in AMD style.
For instance:
math.js
define([], function () {
return {
func1: function (a, b) {
return a + b;
},
func2: function (c, d) {
return c + d;
},
};
});
I would like to generate a new file in the tests folder with the name (math.js) that will contain the boilerplate code for the unit tests in tdd style for the intern framework.
I have used the intern-generator, a Yeoman generator that will do scaffolding and generate a test file with a specified name and path, however, this one won't let me create unit tests that refer to the functions from the JS file.
So, for the math.js source file, I'd like to create a test file (automatically):
define(function (require) {
var tdd = require('intern!tdd');
var assert = require('intern/chai!assert');
var math = require('src/app/math');
tdd.suite('Suite name', function () {
tdd.test1('Test foo', function () {
math.func1('breaks');
});
tdd.test('Test bar', function () {
math.func2('breaks');
});
});
});
This way, I can start with all unit tests files pre-created and I know that all my unit tests will initially break and I will make them pass one by one. Also, this way I can be sure that I got all functions from my source script files into tests.
Naturally, I would like to generate those tests .js files for all my source .js files. Is there any generator or a library/script that will let me do this?

How to set execution order of mocha test cases in multiple files

I have two javascript files which contain mocha test cases.
//----------abc.js -------------
describe("abc file", function(){
it("test 1" , function(){
assert.equal(20 , 20);
});
});
//---------xyz.js--------------
describe("xyz file", function(){
it("test 1" , function(){
assert.equal(10 , 10);
});
});
I have put them in a folder called test and when I execute the mocha command the first file(abc.js) is always executed before xyz.js.
I thought this might be due to alphabetical ordering and renamed the files as
abc.js => xyz.js
xyz.js => abc.js
but still, the content of the xyz.js (previously abc.js) is executed first. How can I change the execution order of these test files?
In the second file, require the first one:
--- two.js ---
require("./one")
or if you are using ES modules:
--- two.js ---
import "./one"
Mocha will run the tests in the order the describe calls execute.
I follow a totally seperate solution for this.
Put all your tests in a folder named test/ and
Create a file tests.js in the root directory in the order of execution
--- tests.js ---
require('./test/one.js')
require('./test/two.js')
require('./test/three.js')
And in the tests files one.js, two.js and so on write your simple mocha tests
this way if you want to run them in the order you have defined then just run mocha tests.js
Mocha has a --sort (short -S) option that sorts test files:
$ mocha --help
[...]
-S, --sort sort test files
[...]
Since mocha sorts files in alphabetical order, I usually prefix my test files names with numbers, like:
0 - util.js
1 - something low level.js
2 - something more interesting.js
etc.
In addition to being really easy to maintain (no gulp grunt or any of that nonsense, no editing your package.json...), it provides the benefit that:
people reading your source code get an idea of the structure of your program, starting from the less interesting parts and moving up to the business layer
when a test fails, you have some indication of causality (if something failed in 1 - something.js but there are no failures in 0 - base.js then it's probably the fault of the layer covered by 1 - something.js
If you're doing real unit tests of course order should not matter, but I'm rarely able to go with unit tests all the way.
If you prefer a particular order, you can list the files (in order) as command-line arguments to mocha, e.g.:
$ mocha test/test-file-1.js test/test-file-2.js
To avoid a lot of typing every time you want to run it, you could turn this into an npm script in your package.json:
{
// ...
"scripts": {
"test": "mocha test/test-file-1.js test/test-file-2.js"
}
// ...
}
Then run your suite from the command line:
$ npm test
Or if you're using Gulp, you could create a task in your gulpfile.js:
var gulp = require('gulp');
var mocha = require("gulp-mocha");
gulp.task("test", function() {
return gulp.src([
"./test/test-file-1.js",
"./test/test-file-2.js"
])
.pipe(mocha());
});
Then run $ gulp test.
The way it worked for my tests to be executed in a specific order was to create a separate test.js file and then added a describe for each mocha test file I'd wanted to execute.
test.js:
describe('test file 1', function() {
require('./test1.js')
})
describe('test file 2', function() {
require('./test2.js')
})
Then simply run mocha test.js
I am exporting an array with all required files and that is the way I tell mocha the order of execution through index.js file in the folder with all my test files:
const Login = require('../login');
const ChangeBudgetUnit = require('./changeBudgetUnit');
const AddItemsInCart = require('./addItemsInCart');
// if the order matters should export array, not object
module.exports = [
Login,
ChangeBudgetUnit,
AddItemsInCart
];
mocha-steps allows you to write tests that run in a specific sequence, aborting the run at the first failure. It provides a drop-in replacement for it, called steps.
Example usage:
describe('my smoke test', async () => {
step('login', async () => {})
step('buy an item', async () => throw new Error('failed'))
step('check my balance', async () => {})
xstep('temporarily ignored', async () => {})
})
The repo hasn't seen much activity in three years, but it works fine with Mocha 9.

Minification of JS file using RequireJS Optimizer

I am working on minification of 3(one.js,two.js,three.js) JS files using require.js. The 3 js files have 3 alert messages. These 3 js files is being called using main.js file.
One.js:
define([], function one() {
alert("one");
});
Two.js:
define([], function two() {
alert("two");
});
Three.js:
define([], function three() {
alert("three");
});
Main.js:
require(["./scripts/one", "./scripts/two", "./scripts/three"], function (one, two, three) {
});
Main_built.js:
define("app/scripts/one",[],function(){alert("one")}),define("app/scripts/two",[],function(){alert("two")}),define("app/scripts/three",[],function(){alert("three")}),require([],function(e,t,n){}),define("app/main",function(){});
Later I created Main_built.js and trying to use it and expecting that no http calls should be made to one,two and three js files, but still I am seeing calls to them in the Fiddler tool.
On running my application, although the Main_built.js is loaded with minified contents of all other js file.
The thing that I am expecting is on executing the application, it should only load the Main_built.js, and should not call any other js files. But i can see it is calling one.js, two.js etc along with Main_built.js
Below is the link I have taken reference from-
http://requirejs.org/docs/optimization.html

How to reuse code in Protractor / AngularJS Testing

We have several Protractor end to end tests for our AngularJS app in several JS files and they work great. But, there is a lot of duplicated code throughout the tests and we would like to DRY that up.
For instance, every time we log in, we have to click on the text elements, type in the username and password, and then click enter. And right now every single JS file has its own copy of the login function which is called before every test.
It would be nice to refactor those out into modules that we can then import. I have been searching for hours, but not found a good solution.
How should we do this?
You can create nodejs modules and include them in protractor configuration
login-helpers.js
exports.loginToPage = function () {
//nodejs code to login
};
protractor.conf.js
exports.config = {
//...
onPrepare: function () {
protractor.loginHelpers = require('./helpers/login-helpers.js');
}
//...
};
page.spec.js
it('should do smth', () => {
protractor.loginHelpers.loginToPage()
//expect(...).toBe(...);
});
Our team uses Orchid-js with Jasmine and Protractor, it's designed to do exactly this.
Your test
Describe('Login user',require('../login.js'))("username","password");
login.js
module.exports = function(username,password){
describe('login the user',function(){
it('should login the user',function(){
element(by.id('usernameField')).sendKeys(username);
element(by.id('passwordField')).sendKeys(password);
element(by.id('loginButton')).click();
});
});
}

Access "global" mocha.js functions when using require.js

I am including Mocha.js with the excellent use shim for a Require.js-based site.
How do I access the define() and it() BDD functions declared by Mocha when using Require.js?
Here is a basic code example:
test.js:
var mocha = require('use!mocha')
, testFile = require('testFile.js')
mocha.setup('bdd');
mocha.run();
testFile.js:
define(function(require) {
// describe() and it() are not available
describe('Book', function() {
it('should have pages', function() {
});
});
});
I get the error Uncaught ReferenceError: describe is not defined when running in the browser.
I have tried window.describe and tried moving the require('testFile.js') to after the mocha.setup('bdd'). I know I am missing something. Probably passing the context to mocha somehow.
The problem is that the global functions such as describe and it are set up by mocha.setup(). You can use shim config's init property to call mocha.setup() before mocha is exported.
requirejs.config({
shim: {
'mocha': {
init: function () {
this.mocha.setup('bdd');
return this.mocha;
}
}
}
});
require(['mocha', 'test/some_test'], function (mocha) {
mocha.run();
});
Test files need to require mocha.
define(['mocha'], function (mocha) {
describe('Something', function () {
// ...
});
});
Shim config's init property was introduced in RequireJS 2.1. You might be able to use exports property instead of init with RequireJS 2.0.
I found the solution in geddski's amd-testing examples project.
Instead of including the test file(s) at the top along with mocha like so:
define(['use!mocha', 'testFile'],
function(Mocha, TestFile) {
mocha.setup('bdd');
mocha.run();
});
The test file(s) should be included as another require call and mocha.run() embedded in the callback:
define(['use!mocha'],
function(Mocha) {
mocha.setup('bdd');
// Include the test files here and call mocha.run() after.
require(['testFile'],
function(TestFile) {
mocha.run();
});
});

Categories