2017-03-31 88 views
7

我有一個使用反應路由器一個簡單的組件(我知道這是alpha版本):測試組件,玩笑和酶

{props.app && props.app.health && 
    <Match exactly pattern="/" component={HomeLogin} /> 
} 

到該文檔推薦在包裝<MemoryRouter />在測試時爲組件提供上下文。

然而,玩笑/酶我無法shallow()渲染 - 我必須使用酶的mount()render(),這會導致問題,因爲HomeLogin是連接的組件 - 我希望能夠來測試我的組件呈現正確的事情,但不是測試其中呈現的組件。

我的測試:

it('Renders based upon matched route',() => { 
    let props = { 
    app: { health: true }, 
    }; 
    const component = render(
    <Provider store={store}> 
     <MemoryRouter location="/"> 
     <Jumbotron {...props} /> 
     </MemoryRouter> 
    </Provider> 
); 
    expect(toJson(component)).toMatchSnapshot(); 
}); 

如何測試基於此路由組件的輸出,而不必提供了Redux商店或使用淺呈現?

更新:如果我嘗試使用shallow(),快照將不呈現輸出。

+2

您是否找到了解決方案? – ridermansb

回答

1

您可以使用.find(Jumbotron),並用這些作爲快照匹配,例如:

const wrapped = component.find(Jumbotron); 
expect(toJson(wrapped)).toMatchSnapshot(); 

我有一個涉及withRouter()更復雜的例子,我被恢復爲快照匹配之前去除輸出的所有鍵。那麼,直到對React-Router v4的測試通過Jest和快照測試變得更加穩固。例如:

export function removeKeys(object) { 
    if (object === undefined || object === null) { 
     return object; 
    } 
    Object.keys(object).forEach((key) => { 
     if (typeof object[key] === 'object') { 
      removeKeys(object[key]); 
     } else if (key === 'key') { 
      delete object[key]; 
     } 
    }); 
    return object; 
} 

... 

expect(removeKeys(toJson(component))).toMatchSnapshot();