我有一个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."
即使不符合条件,它似乎仍在加载样式化组件的子代。我将如何测试呢?
答案 0 :(得分:0)
您正在使用属性hide映射为“ display:none”(当为true时,这仍会渲染该组件,尽管它是无形的),您应该改为执行以下操作:
{ status === "error" &&
<ErrorNotification >
Sorry, something was wrong with your payment. Please try again.
</ErrorNotification>
}
答案 1 :(得分:0)
您的代码按预期工作,只是styled()
通过将类名放在元素上来控制样式而起作用。
在单元测试中ErrorNotification
仍然存在,但是上面有css类,它将在最终呈现的HTML中为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
根本不会呈现。