18

我正在使用 JestJS (npm jest-cli)构建单元测试,并且需要验证 ReactJS 元素是否包含我正在寻找的 CSS 样式。

我试着检查

it('should highlight the selected option in the drop-down list', function() {
    var iconTriangleDown = TestUtils.findRenderedDOMComponentWithClass(dropList, 'icon-triangle-down');

    var iconHeight = window.getComputedStyle(iconTriangleDown.getDOMNode(), null).height;

    expect(iconHeight).notToEqual(''); 
});

这导致 iconHeight === '' 而不是像素值。

我想知道窗口是否被 Jest 嘲笑。或者如果不支持窗口。

4

3 回答 3

14

使用jest-domreact-testing-library相当容易。

小例子:

组件.js

const Component = () => <div style={{left: '4rem'}}>Left component</div>;

组件.test.js

test("left shoud be 4rem", () => {
    const { getByText } = render(<Component />);
    expect(getByText(/left component/i).parentElement).toHaveStyle(`left: 4rem`);
})
于 2018-10-24T08:37:28.990 回答
6

对于找到此线程的任何人,Jest Enzyme 现在有一个断言来测试样式:toHaveStyle:https ://github.com/blainekasten/enzyme-matchers/blob/master/README.md#tohavestylestylekeystring-stylevalueany

对我来说,问题是从查看代码来看,只是测试对象,而且我有很多样式是数组(我使用的是 React Native BTW),所以它对我不起作用。

我正在使用这种方法来测试特定样式:

const render = wrapper.dive();
expect(render.find("[testID='bannerStamp']").get(0).props.style[0].right).toBe(7);
于 2017-12-29T04:58:25.587 回答
2

您可以通过快照测试来测试样式,但 Jest 不支持通过断言评估组件样式——也就是说,通过expect.

为此,您需要将 Jest 与酵素chai-enzyme结合使用。

这种组合将允许您编写类似以下简单示例的测试:

it('should render style', () => {
  chai.expect(shallow(
    <div
      style={{
        left: '4rem'
      }}
    />
  )).to.have.style('left', '4rem');
});

首先,创建一个设置文件并将其添加到jest.setupFilespackage.json 中的数组中。有关此选项的概述,请参阅Jest 文档。

这是我的设置文件:

// test/setup.js
import React from 'react';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow, render, mount } from 'enzyme';

// Add commonly used methods and objects as globals
global.chai = chai;
global.mount = mount;
global.React = React;
global.render = render;
global.shallow = shallow;

chai.use(chaiEnzyme());

这是我的 package.json:

{
  "jest": {
    "setupFiles": [
      "./test/setup.js"
    ]
  }
}

现在,在必要时,您可以通过 访问 Chai 断言 APIchai.expect和通过expect.

于 2017-01-04T04:43:59.727 回答