jbrumwell / mock-knex

A mock knex adapter for simulating a database during testing
MIT License
239 stars 71 forks source link

Mocking various scenarios for Mocha #79

Open boriskogan81 opened 6 years ago

boriskogan81 commented 6 years ago

I'm using Bookshelf and trying to mock two different scenarios for a function which sets up an endpoint.

The data passed into the function is the same for both scenarios; the only difference is that in the second scenario, one of the returned objects has a different value for a property that tells us how many endpoints are already registered, which should then trigger an error telling us the limit has been reached.

I've created arrays of mock return functions, and am passing them into the test. Unfortunately, they both trigger the limit error. It feels like I don't understand the way Mock-Knex is loading the arrays.

Here are my return function arrays:

const successfulSetupTokenFetch = () => {
    query.response([{
        'endpoint_limit': 20,
        'endpoints_registered': 1
    }]);
};

const maxEndpointsSetupTokenFetch = () => {
    query.response([{attributes:{
            'endpoint_limit': 20,
            'endpoints_registered': 21
        }
    }]);
};

const successfulNewSetupQueries = [
    successfulSetupTokenFetch,
    ...
];

const endpointLimitSetupQueries = [
    maxEndpointsSetupTokenFetch,
    ...
];

And here are my tests:

describe('Endpoint setup function', function () {
    mockDb.mock(db);
    it('should create and return a new access token when given proper inputs', async function () {
        tracker.install();
        tracker.on('query', function sendResult (query, step) {
            successfulNewSetupQueries[step - 1]();
        });
        const setupReturn = await setupEndpoint(goodSetupObject);
        assert.equal(typeof setupReturn.token, 'string');
        tracker.uninstall()
    });
    it('should return an endpoint limit error when the limit is reached', async function () {
        tracker.install();
        tracker.on('query', function sendResult (query, step) {
            endpointLimitSetupQueries[step - 1]();
        });
        const endpointReturn = await setupEndpoint(goodSetupObject);
        assert.equal(endpointReturn.error, 'Your organization has reached its endpoint limit. P');
        tracker.uninstall();
    });
    mockDb.unmock(db);
});

Please help me understand what I'm doing wrong.