Ghost/core/test/unit/services/webhooks_spec.js
Kevin Ansfield bffb3dbd90
Webhooks support for subscriber events (#9230)
no issue

Support for http://resthooks.org style webhooks that can be used with Zapier triggers. This can currently be used in two ways:

a) adding a webhook record to the DB manually
b) using the API with password auth and POSTing to /webhooks/ (this is private API so not documented)

⚠️ only _https_ URLs are supported in the webhook `target_url` field 🚨

- add `webhooks` table to store event names and target urls
- add `POST` and `DELETE` endpoints for `/webhooks/`
- configure `subscribers.added` and `subscribers.deleted` events to trigger registered webhooks
2017-11-21 15:43:14 +00:00

85 lines
2.5 KiB
JavaScript

var _ = require('lodash'),
should = require('should'),
sinon = require('sinon'),
rewire = require('rewire'),
testUtils = require('../../utils'),
// Stuff we test
webhooks = rewire('../../../server/services/webhooks'),
events = require('../../../server/events'),
sandbox = sinon.sandbox.create();
describe('Webhooks', function () {
var eventStub;
beforeEach(function () {
eventStub = sandbox.stub(events, 'on');
});
afterEach(function () {
sandbox.restore();
});
it('listen() should initialise events correctly', function () {
webhooks.listen();
eventStub.calledTwice.should.be.true();
});
it('listener() with "subscriber.added" event calls api.webhooks.trigger with toJSONified model', function () {
var testSubscriber = _.clone(testUtils.DataGenerator.Content.subscribers[0]),
testModel = {
toJSON: function () {
return testSubscriber;
}
},
apiStub = {
webhooks: {
trigger: sandbox.stub()
}
},
resetWebhooks = webhooks.__set__('api', apiStub),
listener = webhooks.__get__('listener'),
triggerArgs;
listener('subscriber.added', testModel);
apiStub.webhooks.trigger.calledOnce.should.be.true();
triggerArgs = apiStub.webhooks.trigger.getCall(0).args;
triggerArgs[0].should.eql('subscriber.added');
triggerArgs[1].should.deepEqual({
subscribers: [testSubscriber]
});
resetWebhooks();
});
it('listener() with "subscriber.deleted" event calls api.webhooks.trigger with _previousAttributes values', function () {
var testSubscriber = _.clone(testUtils.DataGenerator.Content.subscribers[1]),
testModel = {
_previousAttributes: testSubscriber
},
apiStub = {
webhooks: {
trigger: sandbox.stub()
}
},
resetWebhooks = webhooks.__set__('api', apiStub),
listener = webhooks.__get__('listener'),
triggerArgs;
listener('subscriber.deleted', testModel);
apiStub.webhooks.trigger.calledOnce.should.be.true();
triggerArgs = apiStub.webhooks.trigger.getCall(0).args;
triggerArgs[0].should.eql('subscriber.deleted');
triggerArgs[1].should.deepEqual({
subscribers: [testSubscriber]
});
resetWebhooks();
});
});