起初,我認為我的代碼的其他方面有問題。所以我在一個新創建的專案中創建了一個新的簡化版本的組件并為它撰寫了測驗,但我的間諜仍然沒有被呼叫。
這是我正在測驗的組件:
import React from 'react';
class TextEditor extends React.Component {
handleChange = (e) => {
console.log({ value: e.target.value });
}
render() {
return (
<div>
<input type="text" name="name" id="name" onChange={this.handleChange} />
</div>
);
}
}
export default TextEditor;
這是單元測驗:
import React from 'react';
import { shallow } from 'enzyme';
import TextEditor from '../TextEditor';
describe('TextEditor', () => {
it('handles change event', () => {
const wrapper = shallow(<TextEditor />);
const spy = jest.spyOn(wrapper.instance(), 'handleChange');
wrapper.find('input').simulate('change', { target: { value: 'test value' }});
expect(spy).toHaveBeenCalledTimes(1);
});
});
運行測驗的結果:

當我運行它時,它失敗了,因為沒有呼叫間諜。但請注意,handleChange 函式中的 console.log 陳述句被執行。因此,測驗實際上呼叫了該函式,但間諜未被識別為已被呼叫。
我可能做錯了什么?謝謝你的想法。
uj5u.com熱心網友回復:
該handleChange方法是類屬性,而不是類的實體方法。
如果你堅持使用類屬性,你應該wrapper.instance().forceUpdate()在窺探之后呼叫。見問題#365
例如
TextEditor.tsx:
import React from 'react';
class TextEditor extends React.Component {
handleChange = (e) => {
console.log({ value: e.target.value });
};
render() {
return (
<div>
<input type="text" name="name" id="name" onChange={this.handleChange} />
</div>
);
}
}
export default TextEditor;
TextEditor.test.tsx:
import { shallow } from 'enzyme';
import React from 'react';
import TextEditor from './TextEditor';
describe('TextEditor', () => {
it('handles change event', () => {
const wrapper = shallow(<TextEditor />);
const spy = jest.spyOn(wrapper.instance(), 'handleChange');
wrapper.instance().forceUpdate();
wrapper.find('input').simulate('change', { target: { value: 'test value' } });
expect(spy).toHaveBeenCalledTimes(1);
});
});
測驗結果:
PASS examples/70652888/TextEditor.test.tsx (13.006 s)
TextEditor
? handles change event (100 ms)
console.log
{ value: 'test value' }
at TextEditor.handleChange (examples/70652888/TextEditor.tsx:5:13)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 14.708 s
另外,請參閱此答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/408000.html
標籤:
