lundi 26 février 2018

Jest snapshot test - Error occurs when creating new object in componentDidMount()

I have a component whose root DOM element is a <canvas>. I use the componentDidMount() method to draw an image on the canvas; However, I am using a 3rd-party library, and when the test attempts to create a new object derived from that library, I receive the following error during my test:

TypeError: QR is not a constructor

QR is the name of the class used to instantiate the object from. Here is my component (note that when running the app, there is no error regarding the QR object, it only occurs during the test).

QRCode.js:

import React, { Component } from 'react';
import * as QR from 'qrious';

export class QRCode extends Component {

    render(){
        return (
            <canvas className='QRCode'>
            </canvas>
        );
    };

    componentDidMount() {
        this.drawQRCode();
    }

    drawQRCode() {
        ...
        // the error is occuring here
        let qr = new QR({
            element: canvas,
            value: 'http://example.com/',
            size: canvasSize,
            level: 'H',
            foreground: '#2B2F2B'
        });
        ...
    }

}

QRCode.test.js:

import { QRCode } from './QRCode';
import renderer from 'react-test-renderer';

describe('QRCode', () => {

    it('renders correctly (snapshot test)', () => {
        const tree = renderer
            .create(<QRCode />)
            .toJSON();

        expect(tree).toMatchSnapshot();
    });

});

I tried adding import * as QR from 'qrious'; to the top of the QRCode.test.js file, but it made no difference.

Aucun commentaire:

Enregistrer un commentaire