如何在reactjs中对组件的内联样式进行单元测试?

问题描述 投票:0回答:1

我有一个名为BsButtons的函数,并且在其中有一个具有嵌入式样式的Button。我正在尝试编写一个单元测试,以检查特定的Button是否具有特定的样式。

BsButtons.jsx

import React from 'react';
import { Button } from 'semantic-ui-react';
export const BsButtons = (props) => {
     const { buttonstyle } = props || {}; 
    return(
        <div>
            <Button style={{...buttonstyle,backgroundColor:'#7B4259', boxShadow:'0 3px 0px rgba(123, 66, 89, 0.15)',borderRadius:20, fontWeight:200}} {...props} />
        </div>
    );};

BsButton.test.js

import React from 'react' ;
import { renderer, create } from 'react-test-renderer' ;
import Enzyme, { shallow, mount } from "enzyme";
import BsButtons from '../../src/components/ButtonComponents/BsButtons';
import Adapter from "enzyme-adapter-react-16";
import { Button } from 'semantic-ui-react';

Enzyme.configure({ adapter: new Adapter() });

const tree = create(<BsButtons/>).toJSON();
it('Should have Background color as #7B4259', () => {
        expect(tree.find(Button)).to.have.style('backgroundColor','#7B4259')
    });

我收到tree.find is not a function的错误。

reactjs jestjs enzyme
1个回答
0
投票

.find在当前包装器上起作用。您正在尝试在测试渲染器实例上使用.find(),这就是为什么您会收到tree.find is not a function错误的原因。首先获取组件的包装实例,然后尝试查找样式属性。

尝试这种方式:

import { shallow } from 'enzyme';

let wrapper = shallow(<BsButtons/>);
it('Should have Background color as #7B4259', () => {
  expect(wrapper.find(Button)).to.have.style('backgroundColor','#7B4259');
});
© www.soinside.com 2019 - 2024. All rights reserved.