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: You can fill all the prompts out now or later. Its up to you.
This will result in a file.
Then run:
This will install all the necessary npm packages to run Karma in our Flask application.
We then run:
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:
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:
And then we save and run:
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!