您好,登錄后才能下訂單哦!
要使用Jest測試React組件的CSS in JS,你需要遵循以下步驟:
確保你已經(jīng)安裝了@testing-library/react
和@testing-library/jest-dom
。如果沒有,請運行以下命令進行安裝:
npm install --save @testing-library/react @testing-library/jest-dom
例如,我們創(chuàng)建一個簡單的Button
組件,使用styled-components
庫實現(xiàn)CSS in JS:
// Button.js
import React from 'react';
import styled from 'styled-components';
const StyledButton = styled.button`
background-color: ${(props) => props.primary ? 'blue' : 'white'};
color: ${(props) => props.primary ? 'white' : 'black'};
padding: 8px 16px;
`;
const Button = ({ primary, children }) => {
return (
<StyledButton primary={primary}>{children}</StyledButton>
);
};
export default Button;
在Button.test.js
文件中,編寫測試用例以驗證組件的樣式是否正確應(yīng)用:
// Button.test.js
import React from 'react';
import { render } from '@testing-library/react';
import Button from './Button';
describe('Button', () => {
it('renders a button with the correct styles', () => {
const { getByRole } = render(<Button>Click me</Button>);
const button = getByRole('button');
expect(button).toHaveStyle('background-color: white');
expect(button).toHaveStyle('color: black');
expect(button).toHaveStyle('padding: 8px 16px');
});
it('renders a primary button with the correct styles', () => {
const { getByRole } = render(<Button primary>Click me</Button>);
const button = getByRole('button');
expect(button).toHaveStyle('background-color: blue');
expect(button).toHaveStyle('color: white');
expect(button).toHaveStyle('padding: 8px 16px');
});
});
在命令行中運行npm test
或yarn test
以執(zhí)行測試用例。
這樣,你就可以使用Jest測試React組件的CSS in JS了。注意,這里的示例使用了styled-components
庫,但你可以根據(jù)需要使用其他CSS in JS庫。關(guān)鍵是確保你的測試用例能夠驗證組件的樣式是否正確應(yīng)用。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。