繁体   English   中英

开玩笑:导入的类“未定义”

[英]Jest: Imported class 'undefined'

将Grid类导入到测试文件中,但仍会收到未定义的错误。

导入路径是正确的,但是当我运行Jest时,在控制台中继续出现“ TypeError:无法读取未定义的属性'grid'”和“无法读取未定义的属性'instance'”。

Grid.test.js

import React from 'react';
import {shallow} from 'enzyme';
import Grid from '../../components/Grid';

let grid;

describe('Grid', () => {

    beforeEach(() => {
        grid = shallow(<Grid/>);
    });

    it('renders correctly', () => {
        expect(grid).toMatchSnapshot();
    });

    describe('splitUpTiles', () => {

        it('returns an empty array if a.length === 0', () => {
            expect(grid.instance().splitUpTiles([0,1], 0)).toEqual([]);
        });
    });

});

Grid.js:

import React, { Component } from 'react';
import Tile from './Tile';

class Grid extends Component {

splitUpTiles = (a, l) => {
    if (a.length === 0) return [];
    else return [a.slice(0, l)].concat(this.splitUpTiles(a.slice(l), l));
};

(omitted code for brevity) 

        render() {

(omitted code for brevity)

        return (
        <div>
            <table>
                <tbody>
                {this.createColumns(arrayOfTiles)}
                </tbody>
            </table>
        </div>
     )
   }
 }

export default Grid;

我以相同的方式测试了其他文件,但没有错误。 有人可以解释我要去哪里吗?

我认为是因为嵌套描述。 您可以尝试将您的内部it放到下面的describe吗?

import React from 'react';
import {shallow} from 'enzyme';
import Grid from '../../components/Grid';

describe('Grid', () => {

    let grid;

    beforeEach(() => {
        grid = shallow(<Grid/>);
    });

    it('renders correctly', () => {
        expect(grid).toMatchSnapshot();
    });

    it('returns an empty array if a.length === 0', () => {
         expect(grid.instance().splitUpTiles([0,1], 0)).toEqual([]);
     });

});

我认为beforeEach存在范围问题

根据文档:

“默认情况下,before和after块适用于文件中的每个测试。您也可以使用describe块将测试分组在一起。当它们位于describe块中时, before和after块仅适用于该describe块中的测试 ”。

尝试这个:

describe('Grid', () => {

    let grid; // Move your var inside describe

    beforeEach(() => {
        grid = shallow(<Grid/>);
    });

    it('renders correctly', () => {
        expect(grid).toMatchSnapshot();
    });
    // Delete second describe block
    it('returns an empty array if a.length === 0', () => {
            expect(grid.instance().splitUpTiles([0,1], 0)).toEqual([]);
    });

});

这里检查文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM