Skip to content

cengizcan/webgl-detector

Repository files navigation

WebGL Detector

GitHub npm type definitions

Test & mock friendly WebGL detection utility.

Install

npm install --save webgl-detector

Usage

import { isWebGLSupported, isWebGL2Supported } from 'webgl-detector';

if (isWebGLSupported()){
  // WebGL is supported!
}
// OR for WebGL2
if (isWebGL2Supported()){
  // WebGL2 is supported!
}

Mocking - Jest & React

Create a file at __mocks__/webgl-detector.js. Make sure __mocks__ directory is adjacent to node_modules.

// __mocks__/webgl-detector.js
const webglDetector = jest.genMockFromModule('webgl-detector');

webglDetector.setValue = value => {
  webglDetector.isSupported = value;
};
webglDetector.isWebGLSupported = () => webglDetector.isSupported;
module.exports = webglDetector;

Suppose we have an Container component named AnimationContainer and a renderer container named MyAnimation. If WebGL is supported, AnimationContainer returns MyAnimation component:

import React from 'react';
import { isWebGLSupported } from 'webgl-detector';

import MyAnimation from './MyAnimation';

const AnimationContainer = props => (
  <div>
    {isWebGLSupported() ? (
      <MyAnimation {...props} />
    ) : (
      <div>WebGL is not supported</div>
    )}
  </div>
);
export default AnimationContainer;

In our test file:

describe('<AnimationContainer />', () => {
  // require mocked module with usual value
  beforeEach(() => {
    require('webgl-detector').setValue(true);
  });
  it('should render something if WebGL is supported', () => {
    expect(something).toBe(true); // pseudo expect
  });
  it('should not render something if WebGL is not supported', () => {
    // set module mock value for WebGL disabled case
    require('webgl-detector').setValue(false);
    expect(something).toBe(false); // pseudo expect
  });
});

Learn more on mocking Node modules in Jest documentation

License

MIT © Cengiz Can

CircleCI David David npm bundle size

About

Test & mock friendly WebGL detection utility

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published