繁体   English   中英

单元测试中安装组件的差异

[英]Differences in mounting components in unit testing

因此,随着时间的流逝,我已经看到了多种方法来渲染用于单元测试的组件,所涉及的测试框架是不相关的。我在徘徊以下任何一种方法有什么优点或缺点?

例如,以下任何一种方法都有可能发生内存泄漏吗?

第一种方法,在所有测试和安装之间使用共享变量。 (我可以想到的主要问题是重写默认组件props会很棘手)

describe('some describe', () => {
    let component
    const baseProps = {}

    beforeEach(() => {
        component = shallow(<MyComponent {...baseProps} />)
    })

    it('test 1', () => {
        expect(component).to.something
    })

    it('test 2', () => {
        expect(component).to.something
    })
})

第二种方法,在每次测试开始时调用renderComponent,但仍使用共享变量

describe('some describe', () => {
    let component;

    function renderComponent(props = {}) {
        const baseProps = {}
        component = shallow(<MyComponent {...baseProps} {...props} />)
    }

    it('test 1', () => {
        const props = {}
        renderComponent(props)
        expect(component).to.something
    })

    it('test 2', () => {
        renderComponent()
        expect(component).to.something.else
    })
})

第三种方法,在每次测试中安装组件

describe('some describe', () => {
    const baseProps = {}

    it('test 1', () => {
        const props = {}
        const component = shallow(<MyComponent {...baseProps} {...props} />)
        expect(component).to.something
    })

    it('test 2', () => {
        const props = {}
        const component = shallow(<MyComponent {...baseProps} {...props} />)
        expect(component).to.something.else
    })
})

第四种方法,使用一个辅助函数返回测试实例

describe('some describe', () => {
    function renderComponent(props = {}) {
        const baseProps = {}
        return shallow(<MyComponent {...baseProps} {...props} />)
    }

    it('test 1', () => {
        const component = renderComponent()
        expect(component).to.something
    })

    it('test 2', () => {
        const component = renderComponent()
        expect(component).to.something.else
    })
})

1-在beforeEach创建component ,因此无法在创建之前通过测试对其进行自定义(如您所述)。

2- renderComponent通过副作用起作用...最佳实践是避免它们。

3-工作正常

4-正常工作...由于renderComponent是纯函数,因此最好使用2。


由于JestMochaJasmine均在beforeEach钩子之前运行, beforeEach在同一测试中, beforeEach钩子在describe它们并按定义的顺序运行之前,这四个行为相似。

只要您的组件在其自身之后进行清理(例如:在componentWillUnmount清除所有计时器,全局侦听器等),所有这四个都仅使用describe回调本地的变量(在4中,所有内容都更加本地化到测试回调)。在组件上unmount ),这四个都不容易发生内存泄漏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM