Flask and Javascript Testing

Oh My!

Posted by Andrew Graham-Yooll on February 20, 2018

There comes a time in a Flask applications lifecycle where javascript testing may become necessary. You might have lots of jQuery laying around. Or get that sneaking feeling like you are going to start adding some Vue.js code into your project.

For whatever reason, you’ll be happy to know that it’s not a huge undertaking and can be quite simple and highly effective.

For this example I have used the Flaskr example from the official Flask repository.

Once you have your project, lets get started!

While you are in the root directory, you will want to run:

npm init
You can fill all the prompts out now or later. Its up to you.

This will result in a

package.json
file.

Then run:

npm install karma karma-chrome-launcher karma-jasmine jasmine-core karma-browserify watchify requirejs --save-dev

This will install all the necessary npm packages to run Karma in our Flask application.

We then run:

karma init

This will prompt you with a bunch of questions. You can answer them as you like.

For this post, there are two questions that concern me:

  1. Do you want to use Require.js ? > yes
  2. What is the location of your source and test files ? > test/**/*.spec.js

That just means that we are going to look and put all our javascript tests into a test/something directory. And importantly, the test names all end with spec.js. For example, something.spec.js

We can then test it out by creating a test in the something.spec.js file:

describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
});

And then we save and run:

karma start

Voila! Our tests should pass with green.

Another cool thing about this set up is that the code will be watched. So when you change any files, the tests will rerun to make sure everything is still passing.

I recommend you read through the Jasmine and Karma docs. You can do a lot of cool stuff in the karma.config.js file.

I’ll post some more on that later!