Skip to content
Discussions/App Development/How to mock useStreamQueries in jest test?Forum ↗

How to mock useStreamQueries in jest test?

App Development4 posts1,368 views5 likesLast activity Feb 2021
RI
Richard_KapolnaiOP
Feb 2021

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);
});
CO
cocreature
Feb 2021

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.

RI
Richard_Kapolnai
Feb 2021

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);
});
CO
cocreature
Feb 2021

Nice work! glad that you figured it out.

← Back to Discussions