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
添加回答
舉報