Flask and Javascript Testing
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: {% highlight bash %}npm init{% endhighlight %} You can fill all the prompts out now or later. Its up to you.
This will result in a {% highlight bash %}package.json{% endhighlight %} file.
Then run:
{% highlight bash %} npm install karma karma-chrome-launcher karma-jasmine jasmine-core karma-browserify watchify requirejs --save-dev{% endhighlight %}This will install all the necessary npm packages to run Karma in our Flask application.
We then run:
{% highlight bash %} karma init{% endhighlight %}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:
- {% highlight bash %}Do you want to use Require.js ? > yes{% endhighlight %}
<li>{% highlight bash %}What is the location of your source and test files ? > test/**/*.spec.js{% endhighlight %}</li>
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:
{% highlight javascript %} describe("A suite", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); });{% endhighlight %}
And then we save and run:
{% highlight bash %}karma start{% endhighlight %}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!