Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: MediaStream is not defined - in unitTest with Jest

I am trying to run unit-test with jest framework. I have some webrtc related code in my project written in typescript.

I am continuously getting this error. I tried to mock MediaStream but to no avail.

My test file:

import * as React from "react";
import * as renderer from 'react-test-renderer';
import { Provider } from 'react-redux';
const configureStore = require('redux-mock-store');


import App from '../App';
import mockData from "../mockData";
const mockStore = configureStore();

describe('Tests related to App', () => {
    it('Capturing Snapshot of App', () => {
        let store = mockStore(mockData.getStore());
        const renderedValue = renderer.create(<Provider store={store}><App /></Provider>).toJSON();;
        expect(renderedValue).toMatchSnapshot();
    });
})

I understand that MediaStream is a platform level property. So i tried to mock, such that Jest would understand, but to no avail.

My mock code.

let mediaStream = {
        getVideoTracks: function() {
            return [];
        }
    }

    const mediaDevicesMock = {
        getUserMedia: jest.fn(() => { return Promise.resolve(mediaStream)})
      };

    global.navigator.mediaDevices = mediaDevicesMock;

I may be wrong on multiple levels, any suggestion and rectification is most welcome. I tried to make sense of this link, but not much could be figured out.

Jest Version: "^22.1.4"

like image 212
Gyanesh Gouraw Avatar asked Aug 09 '19 05:08

Gyanesh Gouraw


1 Answers

I have mocked MediaRecorder in order to pass test like this:

Object.defineProperty(window, 'MediaRecorder', {
    writable: true,
    value: jest.fn().mockImplementation((query) => ({
        start: jest.fn(),
        ondataavailable: jest.fn(),
        onerror: jest.fn(),
        state: '',
        stop: jest.fn()
    }))
});

Additionally, I have also mocked the isTypeSupported method:

Object.defineProperty(MediaRecorder, 'isTypeSupported', {
    writable: true,
    value: () => true
});
like image 95
Juraj Bublinec Avatar answered Oct 06 '22 05:10

Juraj Bublinec