davideweaver
4/21/2020 - 12:08 PM

Mocha test with stubs

// tslint:disable:no-unused-expression
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';

import ServiceRequest from '../../../src/lib/ServiceRequest';
import { BlacklistService } from '../../../src/services/blacklistService';
import * as testUtils from '../../../test/lib/testUtils';

chai.use(chaiAsPromised);
const expect = chai.expect;
const sandbox = sinon.sandbox.create();

afterEach(() => {
    sandbox.restore();
});

describe(testUtils.getDescribeName(__filename), () => {

    describe('blacklistService', () => {

        it('should check blacklist', async () => {

            const ip = '192.168.1.12';
            const postResult = { allowed: true };
            const stubPost = sandbox.stub(ServiceRequest.prototype, 'post').resolves(postResult);

            const service = new BlacklistService();
            const result = await expect(service.isAllowed(ip)).to.be.fulfilled;

            expect(stubPost.callCount).to.equal(1);
            expect(result).to.equal(postResult.allowed);
        });

        it('should swallow errors', async () => {

            const ip = '192.168.1.12';
            const err = new Error('bad');
            const stubPost = sandbox.stub(ServiceRequest.prototype, 'post').throws(err);

            const service = new BlacklistService();
            const result = await expect(service.isAllowed(ip)).to.be.fulfilled;

            expect(stubPost.callCount).to.equal(1);
            expect(result).to.equal(true);
        });
    });
});