Search code examples
javascriptunit-testinghapi

Unit testing Hapi Server Methods


I have an app that's making heavy use of Hapi's Server Methods. The methods are being applied via an exported register function, and the code that's being executed for the method is in the same file and thus not exported. I'm trying to write tests for these methods without exporting the functions that they call in the simplest possible way, but I haven't found any examples of how to do so.

export function register(server) {
  server.method(
    'methodNameA',
    async (path, {}) => {
      // Some code here
      return something; // I want to test this result
    },
    {
      cache: methodCache.halfDay,
      generateKey(path, { ... } = {}) {
        return something;
      },
    }
  );
};

Abstracting that logic is an option, but I'd rather not expose it just for a test. I'd also prefer to not test an entire route just to validate this bit of logic (though that may be the ultimate solution here).


Solution

  • I will use jestjs as my unit testing framework. You can provide a mocked server and a mocked implementation for server.method(). Then you can get the original method in your test case. After getting the original method, test it as usual.

    E.g.

    register.ts:

    export function register(server) {
      server.method('methodNameA', async () => {
        return 'something';
      });
    }
    

    register.test.ts:

    import { register } from './register';
    
    describe('67093784', () => {
      it('should pass', async () => {
        let methodNameA;
        const mServer = {
          method: function mockImplementation(m, func) {
            methodNameA = func;
          },
        };
        register(mServer);
    
        // test method
        const actual = await methodNameA();
        expect(actual).toEqual('something');
      });
    });
    

    unit test result:

     PASS  examples/67093784/register.test.ts (11.981 s)
      67093784
        ✓ should pass (3 ms)
    
    -------------|---------|----------|---------|---------|-------------------
    File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -------------|---------|----------|---------|---------|-------------------
    All files    |     100 |      100 |     100 |     100 |                   
     register.ts |     100 |      100 |     100 |     100 |                   
    -------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        14.766 s