acvetkov / sinon-chrome

Testing chrome extensions with Node.js
ISC License
437 stars 48 forks source link

How to run the example code? #29

Closed webkhung closed 8 years ago

webkhung commented 8 years ago

Hi, I am new to Javascript testing. I have a chrome plugin and I want to write some unit tests to it.

I tried your "Usage example" but couldn't get the testing part to work. I don't know where to put the reference to the "sinon-chrome.latest.js". Also, how do I know if the tests are run? I am very confused on how sinon knows that it needs to run background.test.js and popup.test.js. And where can I see the test result?

Thanks

vitalets commented 8 years ago

I agree. We should add ready-to-use example to the project or create another sinon-chrome-example repo.

acvetkov commented 8 years ago

@webkhung you can use any test environment.

For example, mocha + chai. You should read how it works before. sinon-chrome is just stub lib for chrome api methods.

Let's write simple module.

// /src/button.js
module.exports = {
    setIcon: function (iconPath) {
        return chrome.browserAction.setIcon({
            path: iconPath
        });
    }
};

Let's test it. Install before

npm install mocha chai sinon-chrome --save-dev

Our test

// /test/button.test.js
var chrome = require('sinon-chrome');
var assert = require('chai').assert;
var buttonModule = require('../src/button.js');

describe('button', function () {

    before(function () {
        global.chrome = chrome;
    });

    after(function () {
        delete global.chrome;
    });

    describe('setIcon', function () {

        it('should call chrome api with correct args', function () {
            assert.ok(chrome.browserAction.setIcon.notCalled, 'setIcon method not called');
            buttonModule.setIcon('my/icon.png');
            assert.ok(chrome.browserAction.setIcon.withArgs({path: 'my/icon.png'}).calledOnce, 'setIcon method called once');
        });
    });
});

Write test run configuration. In your package.json add script

{
    "scripts": {
        "test": "mocha ./test/button.test.js"
    }
}

Now, you can run your tests by cli

npm test
webkhung commented 8 years ago

@acvetkov Thank you very much for your reply. I am a newbie in JS testing, your reply definitely help. I will try that! Thanks again.