Jest:如何测试依赖于文档

时间:2018-03-21 13:32:38

标签: unit-testing jest

Heyo。

我想开始为我的代码编写单元测试。我以为我会从一个简单的功能开始。

string =>串

在这里采取行动:http://jsbin.com/yufuzawalo/edit?js,console,output

const animEndString = (type = 'transition') => {
    let types =
        type === 'transition'
            ? {
                OTransition: 'oTransitionEnd',
                WebkitTransition: 'webkitTransitionEnd',
                MozTransition: 'transitionend',
                transition: 'transitionend'
            }
            : {
                OAnimation: 'oAnimationEnd',
                WebkitAnimation: 'webkitAnimationEnd',
                MozAnimation: 'animationend',
                animation: 'animationend'
            }

    const elem = document.createElement('div')

    return Object.keys(types).reduce(function(prev, trans) {
        return undefined !== elem.style[trans] ? types[trans] : prev
    }, '')
}

测试:

describe('example', () => {
    it('should return animationend when passed the string animation', () => {
        const value = animationEnd('animation')

        expect(value).toBe('animationend')
    })

    it('should return transitionEnd when passed the string animation', () => {
        const value = animationEnd('transition')

        expect(value).toBe('transitionend')
    })
})

输出:

example › should return transitionEnd when passed the string animation

    expect(received).toBe(expected) // Object.is equality

    Expected value to be:
      "transitionend"
    Received:

测试失败,因为正在返回emptry字符串。 我假设jest不知道如何处理document.createElement('fake')

我如何解决这个问题?

先谢谢了...在测试方面,我总是一个菜鸟。

1 个答案:

答案 0 :(得分:1)

...解决

我已将以下内容添加到我的setup-jest文件

global.document.createElement = jest.fn(() => ({
    style: {
        transition: 'opacity 300ms ease',
        animation: 'test 300ms'
    }
}))