Ответ 1
Вы можете использовать этот метод. Он возвращает ReactElement.
let containerStyle = container.get(0).style;
expect(containerStyle).to.have.property('opacity', '1');
Я пытаюсь проверить атрибут стиля для компонента React. Каков наилучший способ получить параметры стиля в тесте?
В этот момент мой лучший вариант - проверить, содержит ли HTML строку, но я думаю, что есть лучший вариант.
Случай:
it('Should render large image when desktop', () => {
const dummyUrl = 'http://dummyUrl';
const wrapper = shallow(
<MockedStore
initialState={{
app: fromJS({ browser: { desktop: true } }),
}}
>
<LandingHero bigImage={dummyUrl} />
</MockedStore>
);
});
Компонент для тестирования:
// @flow
import React, { Component } from 'react';
import gc from 'styles/core.scss';
import $ from 'jquery';
import DownloadButton from 'components/DownloadButton';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import DownArrow from 'components/DownArrow';
import { connect } from 'react-redux';
import type { Map } from 'immutable';
import c from './styles.scss';
@withStyles([gc, c])
@connect(({ app }) => ({ app }))
class LandingHero extends Component {
componentDidMount() {
if ($(window).height() > 0) { // Necesary for webpack dev server
$(this.hero).css('height', $(window).height() - 46);
}
}
hero: HTMLElement;
props: {
app: Map<string, any>,
copy: string,
secondaryText: string,
thirdText: string,
bigImage?: string,
smallImage: string,
}
render() {
const { copy, secondaryText, thirdText } = this.props;
const browser = this.props.app.has('browser') ? this.props.app.get('browser') : {};
const backgroundImage = browser.desktop ? this.props.bigImage : this.props.smallImage;
return (
<div
className={`${c.hero} ${gc.textCenter}` +
` ${gc.alignMiddle} ${gc.alignCenter} ${gc.row} ${gc.expanded}`}
ref={(hero) => { this.hero = hero; }}
style={{
margin: 0,
position: 'relative',
background: `linear-gradient(to bottom, rgba($ixdarkprimary, .3), rgba($ixdarkprimary, .3)), url(${backgroundImage || ''})`,
}}
>
<div className={`${gc.row} ${gc.alignCenter} ${gc.alignMiddle} ${gc.column} ${gc.medium10}`}>
<div className={`${gc.textCenter}`}>
<div
className={`${gc.white} ${c.mainText} ${c.copy}`}
>
{ copy }
</div>
<div className={`${gc.small6} ${gc.smallOffset3} ${gc.medium4} ${gc.mediumOffset4}`} style={{ marginBottom: 45 }}>
<DownloadButton />
</div>
<div className={`${gc.white} ${gc.fontBold} ${gc.font24}`}>{secondaryText}</div>
<p className={`${gc.white} ${gc.font20}`}>{thirdText}</p>
</div>
<DownArrow goTo="#content" />
</div>
</div>
);
}
}
export default LandingHero;
Вы можете использовать этот метод. Он возвращает ReactElement.
let containerStyle = container.get(0).style;
expect(containerStyle).to.have.property('opacity', '1');
Немного уточняя ответы других:
expect(component.find('#item-id').prop('style')).toHaveProperty('backgroundSize', '100%');
Это проверит опцию style
#item-id
. Эта поддержка является объектом, и здесь toHaveProperty
проверяет, содержит ли этот объект свойство backgroundSize
, и если его значение 100%
.
Таким образом игнорируются другие свойства стиля.
expect(component.find('#item-id').prop('style')).to.deep.equal({display: 'none'})
Если вы используете jest-styled-components, вы можете использовать toHaveStyleRule
следующим образом:
expect(component.find('#item-id')).toHaveStyleRule('opacity', 'red');
const elem = wrapper.find(Element);
expect(getComputedStyle(elem.getDOMNode()).getPropertyValue('opacity')).toBe('0.4');
Посмотрите на chaiEnzyme, который предоставляет удобное небольшое утверждение, которое вы можете использовать с chai, чтобы проверить, имеет ли оболочка определенный стиль (https://github.com/producthunt/chai-enzyme#stylekey-val), должны помочь сделать ваши тесты немного чище.
Вы можете попробовать использовать значение regex
on .html()
:
const span = mount(<Test />).find('span');
expect(span.html().match(/style="([^"]*)"/i)[1]).toBe('color: #000;');
Или получить любой другой атрибут:
const getAttr = ( html, name ) => html.match(new RegExp(`${name}="([^"]*)"`, 'i'))[1];
let type = getAttr('<input type="text" value=""/>', 'type');
console.log(type); // "text"
Я хотел бы добавить, что следующий метод props()
также может быть использован.
https://airbnb.io/enzyme/docs/api/ShallowWrapper/props.html
let containerStyleOpacity = container.get(0).props().style.opacity;
expect(containerStyleOpacity).to.be.equal('1');