Jasmine is an excellent framework for JavaScript testing, but I had a tough time coaxing it into cooperation with the Chrome extension I was developing. Jasmine's default testrunner uses an inline script block that listens for window.onload
to setup the test environment, but Chrome prohibits extensions from running inline code. Alas, it's not as easy as importing the inline code as a separate file. After a little tinkering, this is what I came up with:
Extension
├── html
├── js
├── manifest.json
└── tests
├── jasmine
│ └── lib
│ └── jasmine-2.5.2
│ ├── MIT.LICENSE
│ ├── jasmine-html.js
│ ├── jasmine.css
│ └── jasmine.js
| └── boot.js
├── loadjasmine.js
├── spec
│ └── YourSpec.js
└── tests.html
The /jasmine/lib
directory includes the contents of the lib
directory in Jasmine's standalone release. tests.html
is a modified test runner and loadjasmine.js
handles the setup. Put your specs in a /tests/spec
directory, or wherever you want to find and import them. You can import the JavaScript code to test against directly from your /js
directory or wherever you've put your background and content scripts.
The modified test runner includes a pair of buttons that set up the Jasmine environment and run the included specs. You might need to stub out some chrome.*
methods, but this makes testing inside the extension as you develop much easier—which made me write more tests and run them more often. I added a link to my tests from my extension's options page so they were always at hand during development.
This is very useful! Thanks!
By chance I found it is possible to run the Jasmine specs even without the 'loadjasmine.js' (only 'tests.html'). I am using Jasmine 2.6.0 on a Mac. I created an option page with the link to the tests.html and it worked even when it can't find loadjasmine.js (I accidentally deleted it).