45 minutes
Here are links to lessons that should be completed before this lesson:
Learn to use more than one testing tool for flexibility.
Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus it's suited for websites, Node.js projects, or anywhere that JavaScript can run.(stackshare.io)
Which companies use Jasmine testing?
Participants will be able to:
- create a testing structure
- create assertion functions
- Generate, display and watch tests
- Jasmine
- install Jasmine
- create tests using
toBe
,beforeEach
,afterEach
- Mocha
- install Mocha
- create tests using assert
- Chai
- install Chai
- require library for assertions
Jasmine is a behavior-driven development (BDD) for testing JavaScript code. Jasmine has no external dependencies and does not require a DOM.
You should write the test first then construct code to pass the test. If developers don't start with test it can be more time consuming to write them later.
install jasmine
npm install --global jasmine
will install jasmine globally.npm install --save-dev jasmine
for testing in your future projects. This saves Jasmine in the project you are using so that it can be shared with others when they clone the repository.
initialize project
jasmine init
will work if jasmine was installed globably.node node_modules/jasmine/bin/jasmine init
will work if jasmine was installed locally.
create files
- In the "./spec" folder create test files that end with "spec.js" so that jasmine knows which files are the test files. For example
string.test.spec.js
.
start test
-
Use
npm test
on the command line. Make sure to run it from the root project directory after including"test": "jasmine"
to thepackage.json
scripts. -
describe
is a function that takes 2 arguments ("STRING", FUNCTION(){}) and multipleit
statements. Insidedescribe
it
will contain the test statements (also known as "specs"). The testing happens in the lineexpect(WORD.length == 4).toBe(true);
. Good test in jasmine should read like a sentence.expect
andtoBe
must be true or the test will fail.
describe("Testing string that",function(){
it("contains 4 letters", function(){
WORD = "word";
expect(WORD.length == 4).toBe(true);
});
});
- multiple
it
statements can use the same variables if they are declared under thedescribe
scope.
describe("Testing string WORD",function(){
let WORD = "supertestinghasbegun" // failing from the start
it("contains 4 letters", function(){
WORD = "word";
expect(WORD.length == 4).toBe(true);
});
it("must be null",function(){
WORD = '';
expect(WORD == '').toBe(true);
})
});
including packages in jasmine test
- Require packages you need in your test at the top of the spec file. Files/modules that are being tested need to have a
module.exports
in them. Then they can be required in the spec file.
// ...spec.js
const app = require('./server');
const config = require('./config');
// Test app.post or something that must pass test
install Mocha
npm install --global mocha
create test files
- A different
NAME.js
file that will be testing with mocha must be placed in the./test
folder so Mocha can apply the test.
start test
- Add a test script to
package.json
like this"test":"mocha"
. Now when you runnpm test
from the command line it will run the mocha tests. describe
andit
functions work similar to jasmine's similarly named functions.
var assert = require('assert');
describe('Mocha String Test', function () {
it('should return the exact number of characters in a string', function () {
assert.equal("Hello".length, 4); // this line will fail
});
it('should return first character of the string', function () {
assert.equal("Hello".charAt(0), 'H'); // this line will pass
});
});
- When calling
assert.equal()
mocha expects the value to be true or else the test will fail. - Mocha will allow you, the developer, to use other assert libraries. Chai has an assert library that could be used instead, but that does require Chai to be installed. This gives you the developer choice and flexibility.
install Chai
npm install --save-dev chai
setting up Chai
assert
test for truthiness in the statement.
const assert = require("chai").assert;
assert('hi' !== 'good-bye', 'Hi is not good-bye');
- Not all testing libraries are created the same. These libraries have different and overlapping functionality.
- Jasmine has test structure, assertions, displays test results, and spies.
- Mocha displays test results
- Chai is an assertion library that can be used with Mocha.
- You can get "false positives" and "false negatives" in tests.
- A test with no exceptions in it will pass. (false positive)
- Pay attention when writing test for Synchronous vs Asynchronous code. The testing engine might complete before the code has completed running, giving you unreliable tests.
- Expect inside of asynchronous code is ignored, therefore passing. (false positive)
- Solve this problem ( in jasmine and mocha ) with a parameter like
done
. Signaling to the test engine this is asynchronous code and it must wait. Mocha will also allowreturn Promise
... inside the function which gives a similar signal to the test engine to wait for async code.
FIRST PRACTICE
- Create a project using
npm init
. - Install
jasmine
asdevDependencies
- Create a function in a
myFunction.js
file. Do not complete the function. We will start with the function failing our test. - Setup a test file that will test
myFunction.js
returns the expected value. - Complete the function so that it returns a value and passes the test.
SECOND PRACTICE
- Create a different project using
npm init
. - Install
mocha
, andchai
asdevDependencies
. - Create a function in a
yourFunction.js
file. Same as above do not complete the function. - With Mocha/Chai test that
yourFunction.js
returns a value, use chaiassert
. - Complete the function so that it returns a value and passes the test.
Instructions: Write your own test that validates an email address was passed to the function userEmail(varString)
. The function is passed a string, so create this function and test it.
Instructions: Make your independent practice test run in the browser. The challenge is the environment must be modified for this test to run in the browser instead of the command line.
-
JS testing with Jasmine blog post, link
-
Chai and Mocha blog post, link
-
Video series by "WebDevJourney"
- Node JS - Authentication - Login/Logout Mocha Testing by Web Dev Journey
- github repo with mocha test included, link.
-
Video by Dylan C. Israel Unit Testing in JavaScript and Jasmine starts at 12:00 minutes to show mocha test.
Question: What is Jasmine and how does it work in your project?
Exercise: Each student must pick a matcher, like toBeNull()
. Then describe that matcher to the class and how it should be used. Each student must select a different picker.