【问题标题】:Jest can't mock returned value of functionJest 不能模拟函数的返回值
【发布时间】:2019-05-15 04:47:27
【问题描述】:

鉴于下面的代码,我在 main.js 中有两个函数,我导出了它们,我想测试 getChangedItems 在我传递一个 html 元素的情况下返回正确的字符串。我想模拟theChanger 的返回值,这样我就不必担心getBoundingClientRect(); 错误打击。

TypeError: itemData.getBoundingClientRect is not a function

main.js

export const theChanger = (itemData) => {
 const { top: parentTop, left: parentLeft } = itemData.getBoundingClientRect();
...

    return { isFull: true, isPartial: true};
}

export const getChangedItems = (itemData) => {
    let items = '';
    const changeIdicator = theChanger(itemData); // I want to mock the return value of this
    if(changeIdicator.isFull || changeIdicator.isPartial) {
        let items = "I made it";
    }
   return items
}

main-test.js

import { theChanger, getChangedItems } from './main.js';
test('getChangedItems returns correct data', () =>  {
    const htmlElement = '<div>Some element</div>'

    expect(getChangedItems(htmlElement)).toBe("I made it")
});

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs enzyme


    【解决方案1】:

    你正在传递字符串

     const htmlElement = '<div>Some element</div>'
    

    它实际上不是 HTML 元素。所以它也没有getBoundingClientRect方法。

    也许你可能会以某种方式使用 JSDOM 的 createElement 来创建元素。但我相信出于测试目的,使用仅模拟 HTMLElement 属性的一部分来构造对象会更好。

    就这样:

    const htmlElement = {
        getBoundingClientRect: {top: <what you need>, left: <what you need>}
        ... any other methods expected
    }
    

    为什么这比使用实际的 HTMLElement 构造函数更好?由于您正在测试一些具体的模块而不是 DOM 渲染引擎本身,因此您不必为该条目保留完整且一致的数据。只模拟你需要的更容易。通过查看该模拟,可以更清楚地了解您的模块实际需要什么。您可以提供使用createElement 几乎不可能获得的模拟(例如,getBoundingClientRect 可以返回top: Infinity)。

    【讨论】:

    • 这完全有道理,但如果我根据我的问题模拟theChanger(itemData) 的返回值会不会更容易,因为我将单独测试该函数。我在乎 getChangedItems 返回什么?
    • @Mohammed,我看不出可以从文件中模拟一个函数,同时使用另一个函数而不进行模拟。见长帖github.com/facebook/jest/issues/936
    猜你喜欢
    • 2020-08-04
    • 2021-10-22
    • 2019-10-27
    • 2021-01-22
    • 2022-06-30
    • 1970-01-01
    • 2019-04-12
    • 2022-01-23
    • 2019-03-13
    相关资源
    最近更新 更多