2017-09-11 795 views
0

我有以下組成部分:如何使用Jest獲取DOM節點的樣式屬性?

// Styled component. 
export const StyledBtn = styled.button` 
    height: ${(height) => height}; 
`; 

// Functional component. 
const Btn = ({ height }) => <StyledBtn height={height} />; 

export default Btn; 

我希望能夠檢查的實際高度(DOM)就是傳遞給Btn組件(我不想檢查道具值) 。這是我會怎麼設想的測試看:

test('button renders at the correct height',() => { 
    const btn = mount(<Btn height={20}); 
    const node = findDOMNode(btn); 
    const height = node.getAttribute('height'); 
    expect(height).toEqual('20'); 
}); 

但是,該測試失敗:

expect(received).toEqual(expected) 

    Expected value to equal: 
     "20" 
    Received: 
     null 

任何想法如何測試呢?

+0

我認爲你的'代碼Btn'是錯誤的。你將道具傳遞給'height'屬性。它應該是: 'const Btn = props =>;' – ericgio

+0

是的,對不起,我的錯誤我編輯了問題以顯示正確的語法。問題仍然存在,正確的代碼。 – JoeTidee

+0

有沒有'.props()'函數就像Enzyme中的一樣?你可以使用'.props()。style'如果是的話 – AHB

回答

0

使用庫jest-styled-components。此外,mount()功能安裝功能組件,所以你這時就需要在它find樣式的組件:

import 'jest-styled-components'; 
... 
test('button renders at the correct height',() => { 
    const component = mount(<Btn height={20}); 
    const btn = component.find('button'); 
    expect(btn).toHaveStyleRule('height', '20px'); 
}); 
相關問題