Jasmine - Run your first test

By xngo on August 22, 2019

In this tutorial, I will show you how to run your first Jasmine test using SpecRunner.html.

Your source code

Let's assume that you have the following JavaScript function do display "Hello world!". Save this code in src/hello.js.

function helloWorld() {
    return 'Hello world!';
}

Your Jasmine test

Below is the code to unit test the helloWorld() function using Jasmine. Save this code in spec/hello.spec.js.

describe('Hello world', function() {
    it('says hello', function() {
        expect(helloWorld()).toEqual('Hello world!');
    });
});

Run Jasmine

To run Jasmine, simply add your source files and spec files in the following template. Save it in SpecRunner.html.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Jasmine Spec Runner v3.4</title>
 
    <link rel="shortcut icon" type="image/png"
          href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine_favicon.png">
 
    <link rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine.css">
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/jasmine-html.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.4.0/boot.js"></script>
 
    <!-- include source files here... -->
    <script src="src/hello.js"></script>
 
    <!-- include spec files here... -->
    <script src="spec/hello.spec.js"></script>
 
</head>
<body/>
</html>

Results

Open SpecRunner.html with a browser. The results of your tests will look like the followings.

Jasmine - Tests ran results

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.