【问题标题】:Jest snapshot test - Error occurs when creating new object in componentDidMount()Jest 快照测试 - 在 componentDidMount() 中创建新对象时发生错误
【发布时间】:2018-08-05 18:10:30
【问题描述】:

我有一个组件,其根 DOM 元素是 <canvas>。我使用 componentDidMount() 方法在画布上绘制图像;但是,我使用的是第 3 方库,当测试尝试创建从该库派生的新对象时,我在测试期间收到以下错误

TypeError: QR is not a constructor

QR 是用于实例化对象的类的名称。这是我的组件(请注意,在运行应用程序时,QR 对象没有错误,仅在测试期间发生)。

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();
    });

});

我尝试将import * as QR from 'qrious'; 添加到 QRCode.test.js 文件的顶部,但没有任何区别。

【问题讨论】:

    标签: javascript reactjs testing jestjs snapshot


    【解决方案1】:

    import * as QR from 'qrious' 替换为import QR from 'qrious'

    编辑:

    由于qrious没有默认导出,应改为:

    import { QRious } from 'qrious'

    import { QRious as QR } from 'qrious'

    【讨论】:

    • qrious.js 文件中没有默认导出,所以很遗憾它不会这样工作
    • 在这种情况下尝试import { QRious } from 'qrious'并将其用作new QRious(),或者如果您想保留为QR:import { QRious as QR } from 'qrious'
    猜你喜欢
    • 2020-03-01
    • 2017-08-13
    • 2021-11-07
    • 2019-06-22
    • 2020-05-04
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    相关资源
    最近更新 更多