hapi icon indicating copy to clipboard operation
hapi copied to clipboard

hapi server.method cache not working when testing

Open catalint opened this issue 10 years ago • 2 comments

'use strict';

const Hapi = require('hapi');
const Boom = require('boom');
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();

const it = lab.it;
const expect = Code.expect;

it('should respond with the same result (cached)', ( done ) => {

    const server = new Hapi.Server({ debug: false });

    const handler = ( request, reply ) => {

        server.methods.test(1, ( err, result ) => {

            reply(err ? Boom.badImplementation(err) : result);
        });
    };

    server.method({
        name: 'test',
        method: ( id, next ) => {

            next(null, Date.now());
        },
        options: {
            cache: {
                expiresIn: 60 * 60 * 24 * 1000,
                generateTimeout: 10 * 1000,
                staleIn: 60 * 60 * 3 * 1000,
                staleTimeout: 10 * 1000
            }
        }
    });

    server.connection();
    server.route({ method: 'GET', path: '/', handler: handler });

    server.inject('/', ( firstRes ) => {

        expect(firstRes.statusCode).to.equal(200);

        server.inject('/', ( secondRes ) => {

            expect(secondRes.statusCode).to.equal(200);

            expect(firstRes.payload).to.be.equal(secondRes.payload);

            done();
        });
    });
});

returns

Failed tests:

  1) should respond with the same result (cached):

      actual expected

      "14576219082051457621908223"

      Expected '1457621908205' to equal specified value

expected

✔ 1) should respond with the same result (cached)

catalint avatar Mar 10 '16 15:03 catalint

this happens only when testing, just adding server.start(() => { solves the issue

    server.start(() => {

        server.inject('/', ( firstRes ) => {

            expect(firstRes.statusCode).to.equal(200);

            server.inject('/', ( secondRes ) => {

                expect(secondRes.statusCode).to.equal(200);

                expect(firstRes.payload).to.be.equal(secondRes.payload);

                done();
            });
        });
    });

catalint avatar Mar 10 '16 15:03 catalint

Yes– the caches are started only once the server is initialized. I suggest initializing (server.initialize()) your server if you need to test this.

devinivy avatar Mar 10 '16 15:03 devinivy