首页 > 解决方案 > 如何使用酶和玩笑测试 css 属性?

问题描述

我正在测试组件的 css 属性。例如,我需要检查 <p> 标签的默认“颜色”属性是否为黑色

我尝试使用 props().style 但如果样式不是内联的,它就不起作用。我也尝试过 toHaveStyleRule() 但它也无济于事

//imports----------------------------------------------
import React from 'react';
import {shallow,configure,mount,render} from 'enzyme';
import toJson from 'enzyme-to-json';
import Adapter from 'enzyme-adapter-react-16';
import "jest-styled-components";
//-----------------------------------------------------

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

//-----------------------------------------------------

describe ('Checking if default color of paragraph is black',() =>{

it("doesn't work",()=>{
  expect(
         mount(<p>Lorem Ipsum</p>).find('p')
      ).toHaveStyleRule('color','black');
});

it("also doesn't work",()=>{
  expect(
        mount(<p>Lorem Ipsum</p>).find('p').props().style.color
      ).toEqual('black');
});
});

我希望测试应该通过(因为段落的默认颜色确实是黑色)。

第一个测试失败并显示消息:

No style rules found on passed Component

第二个失败并显示消息

TypeError: Cannot read property 'color' of undefined

标签: reactjsjestjsenzyme

解决方案


推荐阅读