酶在浅层试验中找不到儿童成分

时间:2017-08-31 20:13:52

标签: javascript reactjs unit-testing jestjs enzyme

这不是用酶进行反应/回流测试但没有存储的正确方法,即"dumb"

import React from 'react'
import { shallow, render } from 'enzyme'
import { Controls } from '../Controls' // named export
import LoadingSpinner from '../LoadingSpinner'
let wrapper
let loadingFlags = {
  controls: true
}
describe('<Controls />', () => {
  it('should render only the loading spinner', () => {
    wrapper = shallow(<Controls loadingFlags={loadingFlags} />) // this ensures the spinner will show until data is ready
    expect(wrapper.length).toEqual(1) // test passes
    expect(wrapper.find(LoadingSpinner)).to.have.length(1)
    // ^ TypeError: Cannot read property 'have' of undefined
  })
})

当我记录wrapper.html()时,我可以看到<img class='spinner' />被渲染,但是酶无法找到它作为一个组件。对我来说,docs表明这正是我应该做的。我想我可以检查一个具有该类的孩子,但这似乎比检查组件本身更麻烦,例如Spinner组件中的类更改。

如何测试此子组件的存在?

2 个答案:

答案 0 :(得分:2)

您应该使用mount()。

来自https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md

import test from 'ava';
import React from 'react';
import { mount, shallow, render } from 'enzyme'

import LoadingSpinner, {Controls} from './LoadingSpinner';
// jsdom init start
const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

function copyProps(src, target) {
    const props = Object.getOwnPropertyNames(src)
        .filter(prop => typeof target[prop] === 'undefined')
        .map(prop => Object.getOwnPropertyDescriptor(src, prop));
    Object.defineProperties(target, props);
}

global.window = window;
global.document = window.document;
global.navigator = {
    userAgent: 'node.js',
};
copyProps(window, global);
// jsdom init end

test('<Controls />' , t => {
    let wrapper = shallow(<Controls />);
    let mntWrapper = mount(<Controls />);
    t.true(wrapper.length == 1);
    t.true(wrapper.find(LoadingSpinner).length === 1);

    t.true(mntWrapper.find("img").length === 1);
    t.true(mntWrapper.render().find('img').length === 1);
    // if you need to test attributes check below.
    t.true(mntWrapper.render().find('img')[0].attribs.src.indexOf('foo') >= 0);
});

答案 1 :(得分:0)

该测试适用于shallow,但断言有一个TypeError,因为它不存在 - 看起来你正在使用Jest,但是酶docs使用chai BDD库显示断言

改为使用Jest等效词:

expect(wrapper.find(LoadingSpinner)).toHaveLength(1)