问题描述
我有以下组件的最低测试反应应用程序:
I have a minimum test react app with following component:
import React from 'react';
import $ from 'jquery';
export default class App extends React.Component {
componentDidMount() {
console.log('componentDidMount', $('#helloDiv').length);
}
render() {
return <div id='helloDiv'>
Hello React!
</div>;
}
}
在浏览器中加载时效果很好(Chrome) 。 componentDidMount()中的console.log()打印出1个找到的helloDiv元素
this works fine when loading it in browser (Chrome). The console.log() in componentDidMount() prints out 1 helloDiv element found
但是,如果我使用mocha + enzyme + jsdom运行测试,则相同的console.log App组件中的()打印输出0:
However, if I run the test using mocha + enzyme + jsdom, the same console.log() in App component prints out 0:
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import App from '../src/client/app/first'
describe('first test', () => {
it('should pass', () => {
const app = mount(<App />);
expect(app.find('#helloDiv').length).to.eq(1);
});
});
注意:我对此单元测试没有问题,它正在通过。真正的问题是什么时候< App />使用酶挂载,调用componentDidMount()但是其中的console.log()语句打印出0,而不是1
这里是我如何运行摩卡:
Here is how I run mocha:
mocha --require enzyme/withDom --compilers js:babel-core/register test/index.test.js
任何想法为什么jquery选择器在测试中找不到任何东西?它不应该是摩卡问题,因为如果我改为开玩笑也会出现同样的问题
Any idea why jquery selector doesn't find anything in the test? It should not be mocha issue because the same issue happens if I change to jest
推荐答案
最后发现问题:
Enzyme mount(< SomeComponent />)
默认情况下会执行完整的DOM渲染但不会将渲染的组件插入当前文档(JSDom)。这就是jQuery在当前文档中找不到任何元素的原因
Enzyme mount(<SomeComponent />)
by default will do full DOM rendering but not insert the rendered component into current document (JSDom). That's why jQuery cannot find any element in current document
要完整的DOM渲染并附加到当前文档:
To do full DOM rendering AND attach to current document:
mount(<SomeComponent />, { attachTo: document.getElementById('app') });
其中 app
是jsdom时可用的空div设置:
Where app
is empty div available when jsdom is setup:
global.document = jsdom('<html><head></head><body><div id="app" /></body></html>');
这篇关于jquery不适用于jsdom / enzyme的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!