reactjs - 基于本地存储断言组件行为的更好方法
问题描述
我有一个基于类的组件,我在其中查找 componentDidMount 的 localstorage 中的变量。
如果它存在,我会渲染其他孩子,我会渲染一个表单
我如何为这个组件编写测试用例?我想通过更改本地存储来测试我的组件行为。
解决方案
为读者添加答案
// My Component
export class Test extends Component {
public state = { isAvailable: false }
public componentDidMount() {
const isAvailable = window.localStorage.getItem("is-agreed") === "true";
if (isAvailable) {
this.setState({ isAvailable: true });
return;
}
}
public render() {
const template = <p>Not available</p>
if (this.state.isAvailable) template = this.props.children;
return template;
}
}
// My Test file
describe("Components/Test", () => {
let wrapper: ReactWrapper;
const store = configureStore();
const getComponent = () => {
const mockStore = store({ data: { something: something } });
return mount(
<Provider store={mockStore}>
<Test>
<p id="testChildren">test</p>
</Test>
</Provider>,
);
};
// If I mount component in beforeEach I'm not able to change the localStorage since the lifecyle method is called before "it".
// So I'm mounting the component in each test case after changing the local storage.
// beforeEach(() => {
// wrapper = getComponent();
// });
afterEach(() => {
wrapper.unmount();
});
it("should return the children when agreed", () => {
localStorage.setItem("is-agreed", "true");
wrapper = getComponent();
expect(wrapper.exists("#testChildren")).toBeTruthy();
});
it("should return the children when not agreed", () => {
localStorage.setItem("is-agreed", "false");
wrapper = getComponent();
expect(wrapper.exists("#testChildren")).toBeFalsy();
});
});
// Local storage mock defined globally in setupTests.ts
var localStorageMock = (function() {
var store: any = {};
return {
getItem: function(key: string) {
return store[key];
},
setItem: function(key: string, value: string) {
store[key] = value.toString();
},
clear: function() {
store = {};
},
removeItem: function(key: string) {
delete store[key];
},
};
})();
Object.defineProperty(window, "localStorage", { value: localStorageMock });
推荐阅读
- python - 使用 python 生成 API 代码文档并在 Web 服务器中托管?
- xslt - 从输入消息中获取值(此消息没有任何空间)
- xamarin - Xamarin 表单:内容视图不显示在内容页面中
- python - TypeError:无法腌制 NotImplementedType 对象(在 keras、python 中)
- c# - 来自 Windows 服务的 PostMessage
- intellij-idea - 如何使用 intellij idea 在 yaml 文件中查找特定的属性键?
- java - Android:显示数组中每个值的文本视图(水平)
- java - 如何创建像“Map.Entry”这样的数组
“? - r - 在 R 中运行多个泊松回归模型时的对比错误:
- python - tensorflow-如何使用可变图像的大小进行 conv2d_transpose?