我有一个Charities组件,它显示文本“对不起...”当status属性为=== "error"时:
import React from "react";
import styled from "styled-components";
const Notification = styled.p`
text-align: center;
padding: 10px;
font-family: Raleway;
display: ${props => (props.hide ? "none" : "block")};
`;
const ErrorNotification = styled(Notification)`
background: #e3c7c4;
`;
export const Charities = ({
..., status
}) => (
<Container>
<ErrorNotification hide={status !== "error"}>
Sorry, something was wrong with your payment. Please try again.
</ErrorNotification>
...
</Container>
);
export default Charities;我试着用下面这样的笑话来测试一下:
import React from "react";
import { mount, shallow } from "enzyme";
import { Charities } from "./index";
describe("Charities", () => {
let props;
let mountedCharities;
const charities = () => {
if (!mountedCharities) {
mountedCharities = mount(<Charities {...props} />);
}
return mountedCharities;
};
beforeEach(() => {
props = {
status: undefined,
...
};
mountedCharities = undefined;
});
describe("when status is pending", () => {
beforeEach(() => {
props.status = "pending";
});
it("doesn't render error", () => {
expect(charities().text()).not.toMatch(/Sorry/); // <---------- FAILS
});
});
});我的测试失败了,原因是:
Expected value not to match:
/Sorry/
Received:
"Sorry, something was wrong with your payment. Please try again.Congratulations! You have successfully made a donation."即使在不满足条件的情况下,它似乎也在加载样式组件的子级。我该如何测试呢?
发布于 2018-08-10 05:28:56
您使用的是hide属性,该属性映射到'display: none‘。如果为true,则尽管不可见,但仍会呈现组件。您应该执行以下操作:
{ status === "error" &&
<ErrorNotification >
Sorry, something was wrong with your payment. Please try again.
</ErrorNotification>
}发布于 2018-08-10 05:31:36
您的代码运行正常,只是styled()的工作方式是将类名放在元素上以控制样式。
在单元测试中,ErrorNotification仍然存在,但它具有css类,这些类将在最终呈现的display: none中提供它。
为了使您的组件更容易进行单元测试,我建议在Charities中进行隐藏,如下所示:
import React from "react";
import styled from "styled-components";
const Notification = styled.p`
text-align: center;
padding: 10px;
font-family: Raleway;
display: block;
`;
const ErrorNotification = styled(Notification)`
background: #e3c7c4;
`;
export const Charities = ({
..., status
}) => (
<Container>
{status !== "error" ? null : (
<ErrorNotification>
Sorry, something was wrong with your payment. Please try again.
</ErrorNotification>
)}
...
</Container>
);
export default Charities;这样,如果Charities的道具中的状态不是'error',那么ErrorNotification就不会被渲染。
https://stackoverflow.com/questions/51773809
复制相似问题