Jest - 如何编写期望导入组件的测试?

Jest - How to write test expecting an imported component?

假设我有一个 componentA 具有导入组件,componentBcomponentC

componentA中,我有一个基于道具的组件方法someMethod,它将输出一个导入的组件。

someMethod() {
    const { someProps } = this.props
    if (someProps === 'desktop') {
        return (
            <componentB
                href="www.google.com" 
            >
                {this.children}
            </componentB>
        )
    } else {
        return (
            <componentC
                href="..." 
            >
                {this.children}
            </componentC>
        )
    }
}

如何为此正确编写测试断言?

这是我目前拥有的,但输出不正确。

describe('someMethod', () => {
    it('should output componentB as component if device is "desktop"', () => {
        const wrapper = enzyme.shallow(<ComponentA {...props} />)
        const correctOut = '<ComponentB href="www.google.com"">Blah Blah</ComponentB>'
        const output = wrapper.instance().someMethod()
        expect(output).toEqual(correctOut)
    })
})

您必须将两个组件都渲染得较浅才能获得相同的输出。将浅层组件 (correctOut) 等同于正常渲染的组件 (output) 是不一样的。

describe('someMethod', () => {
    it('should output componentB as component if device is "desktop"', () => {
        const wrapper = enzyme.shallow(<ComponentA {...props} />)
        const correctOut = '<ComponentB href="www.google.com"">Blah Blah</ComponentB>'
        const output = shallow(wrapper.instance().someMethod())
        expect(output).toEqual(correctOut)
    })
})

注意:只有当您在组件内部渲染的 this.children 等于 Blah Blah.

时,这才有效