【发布时间】:2021-09-07 16:48:40
【问题描述】:
我正在尝试为从我创建的 API 数据库中获取数据的提交按钮创建一个测试。我正在努力将假事件输入转换为从我的事件监听器触发的函数的正确格式。目前,我收到错误“TypeError: Cannot read property 'value' of undefined”
这是提交表单时调用的函数,destination 是一个对象,其键为 id,值来自 HTML 上的 value 属性
const selectDestination = (e) => {
e.preventDefault();
let form = document.querySelector('form');
const destination = {
id: form.destination.value
}
console.log(destination)
fetch(`http://localhost:3000/data/${destination.id}`)
.then(r => r.json())
.then(appendPrice)
.catch(console.warn)
}
它的目标是这段 HTML 代码
<form>
<label for="event">Choose a destination</label>
<select name="destination" id="destination">
<option value="1">Paris</option>
<option value="2">Stockholm</option>
<option value="3">Munich</option>
<option value="4">New York</option>
<option value="5">Los Angeles</option>
</select>
<input id = "submit" type="submit">
</form>
这是我试图用玩笑运行的测试
describe('submit event', () => {
it('listens for event when submit button pressed', () => {
const fakeE = {
preventDefault: jest.fn(),
target: {
destination : { value: '1' },
}
}
app.selectDestination(fakeE)
expect(app.selectDestination).toHaveBeenCalled();
})
})
我已经搞砸了一段时间的语法,但仍然无法让它工作。我认为这个问题与我定位 HTML 的方式有关,但我不确定我将如何改变它。任何帮助将不胜感激。
完整代码在我的github上:https://github.com/qlanphere/travelDestinationPrices
【问题讨论】:
标签: javascript html api jestjs dom-events