我正在 React 应用程序中进行单元测试,以验证传入的 prop 函数是否基于另一个 props 值被有条件地调用。我在我的应用程序中使用了 Typescript/Enzyme/Jest,并在Root
我正在测试的组件周围使用了一个包装器来注入 Redux 存储(并在需要时覆盖初始状态)。
import { mount, ReactWrapper } from "enzyme";
import React from "react";
import Login from "src/components/auth/Login";
import Root from "src/Root";
let wrapped: ReactWrapper;
let defaultProps = {
signIn: jest.fn(),
token: null,
};
beforeEach(() => {
wrapped = mount(
<Root>
<Login {...defaultProps} />
</Root>
);
});
describe("on mount", () => {
describe("if no token is supplied to the props", () => {
it("will call the props.signIn() function", () => {
expect(defaultProps.signIn).toHaveBeenCalled();
});
});
});
当我运行测试时toHaveBeenCalled()
(以及toBeCalled()
,都尝试过)没有注册任何呼叫。但是,我提供了一个console.log
在signIn()
函数存在的相同条件下触发的语句。
import React from 'react';
import { AuthState, JWT } from "src/components/auth/types";
import { signIn } from "src/redux/auth";
interface Props {
signIn: () => Promise<void>;
token: null | JWT;
}
class Login extends React.Component<Props> {
/**
* Sign the user in on mount
*/
public componentDidMount(): void {
if (!this.props.token) {
console.log("GETTING HERE");
this.props.signIn();
}
}
public render(): JSX.Elemeent {
// ... More code
}
}
const mapStateToProps = (state: AuthState) => {
return {
token: state.auth.token;
};
};
export default connect(mapStateToProps, { signIn })(Login);
我已经阅读了几篇相关的帖子/文章,但所有不同的配置,例如遍历酶以获得直接道具或利用spyOn
,都失败了。
我唯一能想到的不同之处是我用 包裹了Login
组件Root
,但考虑到我可以看到console.log
被触发,这似乎是在黑暗中完成的拍摄。
谁能告诉我我在这里做错了什么?
最终是我忘记通过mapDispatchToProps
和mapStateToProps
在connect
函数中放置覆盖。这导致我传入的signIn
函数被signIn
文件中导入的操作覆盖。更新ownProps
并有条件地利用传入的值解决了这个问题:
const mapStateToProps = (state: AuthState, ownProps: Props) => {
return {
token: ownProps.token || state.auth.token;
};
};
const mapDispatchToProps = (dispatch: ThunkDispatch<{}, {}, any>, ownProps: Props) => {
return {
signIn: ownProps.signIn || (() => { return dispatch(signIn()) })
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句