如何在 React Native 中使用 TypeScript 为单元测试模拟 React Navigation 的导航道具? [英] How to mock React Navigation's navigation prop for unit tests with TypeScript in React Native?
问题描述
我正在使用 TypeScript 构建 React Native 应用程序.对于我的导航,我使用 React Navigation,对于我的单元测试,我使用 Jest 和 Enzyme.
I'm building a React Native app with TypeScript. For my navigation I use React Navigation and for my unit testing I use Jest and Enzyme.
这是我的一个屏幕 (LoadingScreen.tsx) 的(精简)代码:
Here is the (stripped down) code for one of my screen (LoadingScreen.tsx):
import styles from "./styles";
import React, { Component } from "react";
import { Text, View } from "react-native";
import { NavigationScreenProps } from "react-navigation";
// Is this correct?
export class LoadingScreen extends Component<NavigationScreenProps> {
// Or should I've done:
// export interface Props {
// navigation: NavigationScreenProp<any, any>;
// }
// export class LoadingScreen extends Component<Props> {
componentDidMount = () => {
this.props.navigation.navigate("LoginScreen");
};
render() {
return (
<View style={styles.container}>
<Text>This is the LoadingScreen.</Text>
</View>
);
}
}
export default LoadingScreen;
在尝试测试屏幕时,我遇到了一个问题.屏幕需要一个类型为 NavigiationScreenProps 的道具,因为我正在访问 React Navigations navigation
道具.这是测试文件的代码 (LoadingScreen.test.tsx):
When trying to test the screens I came across a problem. The screens expects a prop with a type of NavigiationScreenProps because I'm accessing React Navigations navigation
prop. Here is the testing file's code (LoadingScreen.test.tsx):
import { LoadingScreen } from "./LoadingScreen";
import { shallow, ShallowWrapper } from "enzyme";
import React from "react";
import { View } from "react-native";
import * as navigation from "react-navigation";
const createTestProps = (props: Object) => ({
...props
});
describe("LoadingScreen", () => {
describe("rendering", () => {
let wrapper: ShallowWrapper;
let props: Object;
beforeEach(() => {
props = createTestProps({});
wrapper = shallow(<LoadingScreen {...props} />);
});
it("should render a <View />", () => {
expect(wrapper.find(View)).toHaveLength(1);
});
});
});
问题是,LoadingScreen
需要一个 navigation
道具.
The problem is, that LoadingScreen
expects a navigation
prop.
我收到错误:
[ts]
Type '{ constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string | number | symbol): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string | ... 1 more ... | symbol): boolean; }' is not assignable to type 'Readonly<NavigationScreenProps<NavigationParams, any>>'.
Property 'navigation' is missing in type '{ constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string | number | symbol): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string | ... 1 more ... | symbol): boolean; }'.
(alias) class LoadingScreen
我该如何解决这个问题?
How can I fix this?
我想我必须以某种方式模拟 navigation
道具.我尝试这样做(如您所见,我在测试中从 React Navigation 导入了 *
),但无法弄清楚.只有 NavigationActions
是远程有用的,但它只包含 navigate()
.TypeScript 期望所有内容,甚至状态,都可以被模拟.如何模拟 navigation
道具?
I think I somehow have to mock the navigation
prop. I tried doing that (as you can see I imported *
from React Navigation in my test), but couldn't figure out. There is only NavigationActions
that is remotely useful but it only includes navigate()
. TypeScript expects everything, even the state, to be mocked. How can I mock the navigation
prop?
编辑 1: 使用 NavigationScreenProps
的方法是否正确,还是应该使用 interface Props
方法?如果是,那么您将如何模拟(它会导致相同的错误).
Edit 1: Is the approach of using NavigationScreenProps
even correct or should I use the interface Props
approach? If yes how would you then mock than (it results in the same error).
编辑 2:将第二种方法与界面和
export class LoadingScreen extends Component<Props, object>
我能够解决"这个问题.我真的不得不像这样模拟导航对象的每个属性:
I was able to "solve" this problem. I literally had to mock every single property of the navigation object like this:
const createTestProps = (props: Object) => ({
navigation: {
state: { params: {} },
dispatch: jest.fn(),
goBack: jest.fn(),
dismiss: jest.fn(),
navigate: jest.fn(),
openDrawer: jest.fn(),
closeDrawer: jest.fn(),
toggleDrawer: jest.fn(),
getParam: jest.fn(),
setParams: jest.fn(),
addListener: jest.fn(),
push: jest.fn(),
replace: jest.fn(),
pop: jest.fn(),
popToTop: jest.fn(),
isFocused: jest.fn()
},
...props
});
问题仍然存在:这是正确的吗?或者有更好的解决方案吗?
The question remains: Is this correct? Or is there a better solution?
编辑 3:回到我使用 JS 的时候,只模拟我需要的属性就足够了(通常只是导航).但是自从我开始使用 TypeScript,我不得不模拟导航的每一个方面.否则 TypeScript 会抱怨组件需要一个不同类型的 prop.
Edit 3: Back when I used JS, it was enough to mock only the property I needed (often just navigate). But since I started using TypeScript, I had to mock every single aspects of navigation. Otherwise TypeScript would complain that the component expects a prop with a different type.
推荐答案
问题
模拟与预期类型不匹配,因此 TypeScript 报告错误.
Issue
The mock does not match the expected type so TypeScript reports an error.
您可以使用类型 any
"选择退出类型检查并让值通过编译时检查".
正如您所提到的,在 JavaScript 中,它只模拟测试所需的内容.
As you mentioned, in JavaScript it works to mock only what is needed for the test.
在 TypeScript 中,相同的模拟会导致错误,因为它与预期的类型不完全匹配.
In TypeScript the same mock will cause an error since it does not completely match the expected type.
在这种情况下,如果您知道某个模拟与预期类型不匹配,您可以使用 any
来允许模拟通过编译时检查.
In situations like these where you have a mock that you know does not match the expected type you can use any
to allow the mock to pass through compile-time checks.
这是一个更新的测试:
import { LoadingScreen } from "./LoadingScreen";
import { shallow, ShallowWrapper } from "enzyme";
import React from "react";
import { View } from "react-native";
const createTestProps = (props: Object) => ({
navigation: {
navigate: jest.fn()
},
...props
});
describe("LoadingScreen", () => {
describe("rendering", () => {
let wrapper: ShallowWrapper;
let props: any; // use type "any" to opt-out of type-checking
beforeEach(() => {
props = createTestProps({});
wrapper = shallow(<LoadingScreen {...props} />); // no compile-time error
});
it("should render a <View />", () => {
expect(wrapper.find(View)).toHaveLength(1); // SUCCESS
expect(props.navigation.navigate).toHaveBeenCalledWith('LoginScreen'); // SUCCESS
});
});
});
这篇关于如何在 React Native 中使用 TypeScript 为单元测试模拟 React Navigation 的导航道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!