用笑话、酶和 css 模块测试反应组件



我有一个使用创建反应应用程序创建的项目。 假设我有一个简单的组件,如下所示 -

import React from 'react';
import React, { useState } from "react";
function Example() {
const [data, setData] = useState(0);
const onClickHandler = () => {
setData(data + 1);
};
return (
<div className="button" onClick={onClickHandler}>
{data}
</div>
);
}
export default Example;

我将像这样测试组件 -

import React from "react";
import { shallow } from "enzyme";
import Example from "./Example";
it("example test", () => {
const wrraper = shallow(<Example />);
wrraper.find(".button").simulate("click");
expect("test somethig");
});

如果我像这样使用 styles.module -

import React, { useState } from "react";
import styles from "./styles.module.scss";
function Example() {
const [data, setData] = useState(0);
const onClickHandler = () => {
setData(data + 1);
};
return (
<div className={styles.button} onClick={onClickHandler}>
{data}
</div>
);
}
export default Example;

我将无法再使用".button"在测试中找到元素,因为当我使用 css 模块时,webpack 会在我的类名中添加一个哈希。 那么如何在使用 css 模块时测试反应组件呢?仅通过向元素添加 Id? 更改我的代码填充错误,因此我将能够对其进行测试。

有许多替代选择器,您可以在此处找到。也就是说,在使用 (s(css 模块时,我倾向于依赖组件中的元素位置:

wrapper.find("div").first()将选择组件层次结构中的第一个div元素(或者在您的示例中,它将选择带有"styles.button"类名的div(。

另一种方法是使用模板文本。在下面的示例中,我基本上创建了一个逃生舱口来选择.some-classname

import React, { useCallback, useState } from "react";
import { button } from "./styles.module.scss";
function Example() {
const [data, setData] = useState(0);
const onClickHandler = useCallback(() => {
setData(prevSate => prevState + 1);
}, [setData]);
return (
<div className={`${button} some-classname`} onClick={onClickHandler}>
{data}
</div>
);
}
export default Example;

最后,你可以使用一个数据属性——比如data-test-id(由于 react-testing-library,它变得越来越流行(来创建一个简单的静态选择器,可以使用额外的 babel 插件将其删除用于生产构建(。

我参加派对有点晚了,但我自己也想知道这一点。你只需要将你的scss模块导入到你的测试文件中,就像这样:

import React from "react";
import { shallow } from "enzyme";
import Example from "./Example";
import styles from "./styles.module.scss
it("example test", () => {
const wrraper = shallow(<Example />);
wraper.find(`.${styles.button}`).simulate("click");
expect("test somethig");
});

最新更新