How to mock useStreamQueries in jest test?

We’d like to render a page in a test which connects to the ledger during rendering.
How would be possible to mock useStreamQueries to always return an empty contract list? We could not figure out how to do this with jest.mock.

The test is:

it('renders without crashing', () => {
  const div = document.createElement('div');
  document.body.appendChild(div);
  ReactDOM.render(
      <Router>
          <App />
      </Router>,
      div);
});
1 Like

We have some tests in the daml repo that mock the underlying functions in @daml/ledger. Maybe that’s a helpful starting point. Depending on your usecase, mocking @daml/react might be a better option.

1 Like

Moritz, that hint was superb! With some extra trick, managed to get the test passed! :partying_face:

The final test is below. The extra members .on and .close are necessary.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router } from "react-router-dom";
import { Stream } from '@daml/ledger';

const mockLedgerFunction = jest.fn();

jest.mock('@daml/ledger', () => class {
  constructor(...args: unknown[]) {
    mockLedgerFunction(...args);
  }

  streamQueries(...args: unknown[]): Stream<object, string, string, string[]>{
    return {...mockLedgerFunction(...args), on: jest.fn(), close: jest.fn()};
  }
});

it('renders without crashing', () => {
  const div = document.createElement('div');
  document.body.appendChild(div);
  ReactDOM.render(
    <Router>
        <App />
    </Router>,
    div);
  ReactDOM.unmountComponentAtNode(div);
});
2 Likes

Nice work! glad that you figured it out.

1 Like