问题描述
react-sweet-state
(https://atlassian.github.io/react-sweet-state/#/testing/actions)并没有提供太多文档来说明如何测试特定的动作调用以及查看其如何影响组件的呈现方式。
示例:
这是我的商店:
import { createStore,createHook,StoreActionApi } from "react-sweet-state";
interface State {
foo: number;
}
type StoreApi = StoreActionApi<State>;
export const initialState: State = {
foo: 0
};
export const actions = {
changeFoo: (num: number) => ({ getState,setState }: StoreApi) => {
setState({
foo: isNaN(+num) ? 0 : num
});
}
};
type Actions = typeof actions;
const Store = createStore<State,Actions>({
initialState,actions,name: "buzzStore"
});
export const useBuzzStore = createHook(Store);
下面有一个Fizz.tsx
组件,它在useEffect
内调用一个动作:
export const Fizz = () => {
const [state,actions] = useBuzzStore();
useEffect(() => {
actions.changeFoo(100);
},[actions]);
return (
<div>
{state.foo > 0 ? <h2>Foo is {state.foo}</h2> : null}
</div>
);
};
如果state.foo
大于零,则组件使用<h2>
的值呈现state.foo
。如果为零,则不呈现任何内容。
如何在笑话和酵素中对此进行测试,使我可以从测试中调用动作,然后编写如下断言:
describe("the fizz component",() => {
let wrapper: ShallowWrapper;
beforeEach(() => {
wrapper = shallow(<Fizz />);
});
afterEach(() => {
wrapper.unmount();
});
it("should not render an h2",() => {
// NO CALL to action.changeFoo();
expect(wrapper.find("h2").exists()).toBeFalsy();
});
it("should render an h2",() => {
const numberForFoo = 100;
// CALL action.changeFoo(numberForFoo)
expect(wrapper.find("h2").text()).toContain("Foo is " + numberForFoo);
});
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)