測驗新手,這是一個使用 redux 的連接組件。我正在測驗是否呼叫了 maskPromoCode 函式。使用當前的測驗代碼,錯誤提示:無法對原始值進行監視;給定的未定義
不明白為什么。謝謝。
組件:
class Textbox extends React.Component {
constructor(props) {
super(props);
}
onChange(e) {
e.preventDefault();
this.setState({
value: this.maskPromoCode(e.target.value)
})
}
maskPromoCode(value) {...}
render() {
return (
<>
<input
...
onChange={e => this.onChange(e)}
/>
</>
);
}
}
const mapDispatchToProps = { setError, setPwError };
export default connect(null, mapDispatchToProps)(Textbox);
測驗檔案
it('invokes the maskPromoCode function with event value', () => {
const funcMock = jest.spyOn(Textbox.prototype, 'maskPromoCode');
const wrapper = mount(
<Provider store={store}>
<Textbox {...baseProps} name="redeem-promo" />
</Provider>
);
const inputField = wrapper.find('input');
const event = {
target: {
value: 'event value',
},
};
inputField.simulate('change', event);
expect(funcMock).toHaveBeenCalledWith(event.target.value);
});
uj5u.com熱心網友回復:
Textbox組件被函式包裹,connect它變成了一個沒有 的 HOCprototype,我猜你在測驗檔案中匯入了 HOC。TextBox測驗檔案中匯入的組件是一個 HOC。TextBox.prototype也是,這undefined就是jest.spyOn拋出錯誤的原因。如果您堅持使用
jest.spyOn()該maskPromoCode方法,則可以使用jest.spyOn(Textbox.WrappedComponent.prototype, 'maskPromoCode'). HOC 上有一個WrappedComponent靜態屬性,可以獲取到原來的組件類。推薦:您正在測驗實作細節,如果使用
jest.spyOn(...),您應該測驗組件行為。
例如
Textbox.jsx:
import React from 'react';
import { connect } from 'react-redux';
class Textbox extends React.Component {
constructor(props) {
super(props);
this.state = { value: '131' };
}
onChange(e) {
e.preventDefault();
this.setState({ value: this.maskPromoCode(e.target.value) });
}
maskPromoCode(value) {
return '***';
}
render() {
return (
<>
<input value={this.state.value} onChange={(e) => this.onChange(e)} />
</>
);
}
}
export default connect(null, null)(Textbox);
Textbox.test.jsx:
import Textbox from './Textbox';
import React from 'react';
import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
describe('70795348', () => {
it('invokes the maskPromoCode function with event value', () => {
console.log(Textbox.WrappedComponent.prototype.maskPromoCode);
const mockStore = configureStore();
const store = mockStore();
const wrapper = mount(
<Provider store={store}>
<Textbox name="redeem-promo" />
</Provider>
);
expect(wrapper.find('input').instance().value).toBe('131');
const event = { target: { value: 'event value' } };
wrapper.find('input').simulate('change', event);
expect(wrapper.find('input').instance().value).toBe('***');
});
});
測驗結果:
PASS stackoverflow/70795348/Textbox.test.jsx
70795348
? invokes the maskPromoCode function with event value (40 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.729 s, estimated 9 s
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417405.html
標籤:
上一篇:我無法創建django專案
下一篇:C 標準的單元測驗
