[英]TypeError: e.preventDefault is not a function while invoke() function
我的組件是
const _onBoldClick = (e) => {
e.preventDefault();
onEnterText(RichUtils.toggleInlineStyle(editorState, 'BOLD'));
}
<button className = "text-button-style" onMouseDown = { e => { _onBoldClick(e)} }>B</button>
我得到錯誤,
TypeError: e.preventDefault is not a function
74 |
75 | const _onUnderlineClick = (e) => {
> 76 | e.preventDefault();
| ^
77 | onEnterText(RichUtils.toggleInlineStyle(editorState, 'UNDERLINE'));
78 |
79 | }
at _onUnderlineClick (src/components/L3_Admin/L4_AnnouncementsTab/L4_AnnouncementsPage.js:76:11)
這是我嘗試過的測試代碼,
it('onmousedown U button', async () => {
let responseData = [
{
}]
const spy = jest.spyOn(axios, 'get');
const preventDefault = jest.fn();
const _onUnderlineClick = jest.fn();
spy.mockImplementation(async() => await act(() => Promise.resolve({ data: responseData })));
const component = mount( <Provider store= {store}>
<AnnouncementsTab /> </Provider>);
component.update();
// expect(component.find('button')).toHaveLength(6);
// expect(component.find('.text-button-style')).toHaveLength(3);
await component.find('.text-button-style').at(0).invoke('onMouseDown',{ preventDefault })(
{
nativeEvent: {
preventDefault,
e: jest.fn(),
_onUnderlineClick: (e)=>{}
}
},
1000
)
});
function 簽名是.invoke(invokePropName)(...args) => Any 。 .invoke .invoke()
方法沒有第二個參數。 您應該將模擬事件 object 傳遞給.invoke()
返回的 function 。
例如
MyComponent.jsx
:
import React from 'react';
export function MyComponent() {
const _onBoldClick = (e) => {
e.preventDefault();
};
return (
<button
className="text-button-style"
onMouseDown={(e) => {
_onBoldClick(e);
}}
>
B
</button>
);
}
MyComponent.test.jsx
:
import { mount } from 'enzyme';
import React from 'react';
import { MyComponent } from './MyComponent';
describe('67817812', () => {
it('onmousedown U button', async () => {
const preventDefault = jest.fn();
const component = mount(<MyComponent />);
component.find('.text-button-style').at(0).invoke('onMouseDown')({ preventDefault });
expect(preventDefault).toBeCalledTimes(1);
});
});
測試結果:
PASS examples/67817812/MyComponent.test.jsx (7.766 s)
67817812
✓ onmousedown U button (36 ms)
-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
MyComponent.jsx | 100 | 100 | 100 | 100 |
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.754 s, estimated 9 s
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.