This tutorial is a very quick and easy step-by-step article on using Jasmine to test your JavaScript files inside a Django app.
Covered in this tutorial:
- Basic setup of Jasmine to use the python_egg to run tests within a Django app
- How to include the
ajax_helper
and use it to mock AJAX requests.
You can get the code for this tutorial from github:
1. Let's set everything up
First. Let's start a blank django app:
django-admin.py startapp jasminetut
Create a quick virtualenv and activate it:
virtualenv env
source env/bin/activate
Install Jasmine python egg:
pip install jasmine
Setup your specs. From the directory that contains manage.py
run:
jasmine-install
This will create:
./spec/javascripts/**
./spec/javascripts/support/jasmine.yml
Assuming we are keeping our static files in a top level static/js
folder, let's do the following:
mkdir -p static/js
touch static/js/hello.js
2. Let's setup jasmine to test our static files
Open ./spec/javascripts/support/jasmine.yml
Edit src_files
so it includes our js files:
src_files:
- js/*.js
(these paths are relative to our /static
root
.. so now we need to set that up:
Edit: src_dir
so that it looks like this:
src_dir: 'static'
Ok. So what we are doing here is: We are telling jasmine that it can find our javascripts in the top level (relative to the location of the spec
folder directory called static. We are telling it to look for source files matching the pattern we define in src_files
.
4. Take it for a spin
To run Jasmine, simple run:
jasmine
then open up 127.0.0.1:8888
You should see a page that says: 0 specs, 0 failures
Great. We're all setup. Now, let's write a quick spec:
touch spec/javascripts/hello_spec.js
Cause we're doing TDD here, let's write a quick test that will fail before implementing our code. Add the following to hello_spec.js
describe("Test hello.js", function() {
it("returns 'hello'");
});
If we now go back to: 127.0.0.1:8888
You should see something like:
1 spec, 0 failures, 1 pending spec
- Test hello.js
- logs 'hello' to the console
Our test is now pending. Let's quickly flesh it out:
describe("Test hello.js", function() {
it("return 'hello'", function () {
var result = Hello.world();
expect(result).toBe("Hello");
});
});
If we reload now, we'll see our spec is failing. Quickly, let's go make it pass. Edit: static/js/hello.js
to look like:
var Hello = {
world : function () {
return "Hello";
}
};
Reload the page, and now you'll see it's passing. Great success :).
In Part two of this tutorial we will explore mocking AJAX requests with jasmine-ajax