【问题标题】:Jest test of submit event "TypeError: Cannot read property 'value' of undefined"提交事件“TypeError:无法读取未定义的属性‘值’”的笑话测试
【发布时间】: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


    【解决方案1】:

    您应该针对选择输入而不是表单元素。在获取请求中,您还应该返回数据并对其进行处理。

    const selectDestination = (e) => {
        e.preventDefault();
        let chooseDestination = document.querySelector('#destination');
        const destination =  {
            id: chooseDestination.value
            }
        console.log(destination)
    
        fetch(`http://localhost:3000/data/${destination.id}`)
        .then(r => r.json())
        .then(data => {
          // do something with data...
        }).catch(error => {
           console.log(error);
        })
    
    }
    

    【讨论】:

    • 嗯我试过了,代码仍然有效,但我的测试仍然收到错误。 expect(received).toHaveBeenCalled() Matcher error: received value must be a mock or spy function Received has type: function Received has value: [Function selectDestination] 看来我的测试格式还是不正确
    • 尝试使用.catch(error) {console.log(error);} 更正捕获。我要编辑我的答案...
    猜你喜欢
    • 2018-10-29
    • 2017-06-27
    • 2021-10-29
    • 2021-10-26
    • 1970-01-01
    • 2021-07-31
    • 2019-07-05
    • 2022-06-28
    • 2019-06-10
    相关资源
    最近更新 更多