[英]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。
由於Jest
, Mocha
和Jasmine
均在beforeEach
鈎子之前運行, beforeEach
在同一測試中, beforeEach
鈎子在describe
它們並按定義的順序運行之前,這四個行為相似。
只要您的組件在其自身之后進行清理(例如:在componentWillUnmount
清除所有計時器,全局偵聽器等),所有這四個都僅使用describe
回調本地的變量(在4中,所有內容都更加本地化到測試回調)。在組件上unmount
),這四個都不容易發生內存泄漏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.