1 回答

TA贡献1793条经验 获得超6个赞
我相信此问题是由于未配置酶适配器造成的。请参阅酶文档以供参考。它说:
要开始使用酶,您只需通过npm安装即可。您需要安装酶以及与您正在使用的反应版本(或其他UI组件库)相对应的适配器。例如,如果您将酶与React 16一起使用,则可以运行:
npm i --save-dev enzyme enzyme-adapter-react-16
安装完成后,您需要将酶配置为在测试中使用它:enzyme-adapter-react-16
import { configure, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
溶液
注意:我在下面使用钩子进行了解释,这可能是超出您问题范围的额外工作。但是,钩子是一个很好的学习工具。使用适配器将调用添加到 Enzyme.configure
可能会解决您的问题。
我根据对组件所做的假设创建了一个工作解决方案,下面是该代码。我在 React 16.13 上这样做,这意味着我可以访问 Hooks API
具体来说,我正在使用使用Ref
钩子。我在函数的主体中创建一个 ref,并为其分配按钮的 ref 值。钩子创建一个 ref,其中分配了通过调用作为调用参数传递的函数返回的值。useRef
ref.current
useRef
为了禁用有问题的按钮,我设置了,它由函数调用返回。disabled={buttonRef.current}
canUpload
形式.js
export default ({
getData: handleClick,
getContent = () => <div>Content</div>,
canUpLoad: checkCanUpload = () => true,
}) => {
const buttonRef = React.useRef(checkCanUpload())
return (
<React.Fragment>
<div className="margin-2-l">Many other nested divs here</div>
<button
type="submit"
className="btn margin-a margin-b margin-c margin-d"
disabled={buttonRef.current}
onClick={handleClick}
>
Load
</button>
<div className="flex padding-t">Many other nested divs here</div>
<button
type="submit"
id="email"
className="btn margin-a margin-b margin-c margin-d"
ref={buttonRef}
disabled={buttonRef.current}
onClick={handleClick}
>
Send
</button>
</React.Fragment>
)
}
形式规格.js
在测试中,我确保调用 where 是 的默认导出。Enzyme.configure({ adapter: new Adapter() })Adapterenzyme-adapter-react-16
import React from 'react'
import { shallow, configure } from 'enzyme'
import MyComponent from './Form'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })
const data = {
name: '',
}
describe('MyComponent tests', () => {
it('should render correctly', () => {
const wrapper = shallow(<MyComponent someData={data} />)
// also tried find('#email') and find('Button#email') not working.
const submitButton = wrapper.find('button#email')
console.log(submitButton.text())
expect(submitButton.prop('disabled')).toBe(true)
})
})
这是运行单元测试的输出:
PASS src/Form.spec.js
MyComponent tests
√ should render correctly (11ms)
console.log src/Form.spec.js:18
Send
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.796s
Ran all test suites related to changed files.
您可以看到控制台输出的,并且测试已通过。Send
演示
请参阅此工作演示:https://codesandbox.io/s/react-playground-mkcgj
使用 CodeSandbox 的注意事项是,由于 React 被包含两次,测试和浏览器渲染将无法同时工作。注释掉测试中的 以检查浏览器输出,在查看测试时,忽略“适配器未定义”,而只查看该测试的测试结果。configure
但是,我建议将沙盒下载为zip(文件>导出到ZIP),然后将内容解压缩到本地文件夹中。 到目录中,并使用 或 安装依赖项。cd
yarn
npm install
然后,运行 或 启动开发服务器。yarn start
npm run start
若要运行测试,请运行 或 。yarn test
npm run test
添加回答
举报