使用Jasmine和TypeScript测试react-native时找不到模块'View' [英] Cannot find module 'View' while testing react-native with Jasmine and TypeScript
问题描述
我正在尝试使用Jasmine测试一个简单(空")的本机组件.但是当我尝试访问任何react-native组件时遇到错误...
I'm trying to test a simple ("empty") react-native component using Jasmine. But I'm getting an error when I try to access any react-native component...
在我的配置文件(jasmine.json)中,我有:
In my configuration file (jasmine.json) I have:
{
"spec_dir": ".",
"spec_files": [
"src/*.spec.tsx"
],
"helpers": [
"./node_modules/ts-node/register.js"
]
}
我的package.json
My package.json
"react": "16.0.0-alpha.12",
"react-native": "0.45.1",
"jasmine": "^2.6.0",
"ts-node": "^3.3.0",
我在package.json上的测试脚本
My test script on package.json
"test": "jasmine --config=jasmine.json"
我的测试
import * as React from 'react';
import App from './App';
import { createRenderer } from 'react-test-renderer/shallow';
import { StyleSheet, Text, View } from 'react-native';
console.log('View', View); // error
错误:
Error: Cannot find module 'View'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.get View [as View] (...\expo-ts-example\node_modules\react-native\Libraries\react-native\react-native-implementation.js:56:23)
at Object.<anonymous> (...\expo-ts-example\src\App.spec.tsx:7:21)
at Module._compile (module.js:571:32)
at Module.m._compile (...\expo-ts-example\node_modules\ts-node\src\index.ts:392:23)
at Module._extensions..js (module.js:580:10)
at Object.require.extensions.(anonymous function) [as .tsx] (...\expo-ts-example\node_modules\ts-node\src\index.ts:395:12)
在我的组件上进行的任何测试均失败,因为它使用的根"元素是View
.
Any tests on my component fail because the "root" element it uses is a View
.
为什么会出现此错误?有什么方法可以用Jasmine代替Jest进行测试吗?
Why do I get this error? Is there any way I can use Jasmine to test instead of Jest?
推荐答案
View
是本机元素,因此,当您在本机环境之外运行Jasmine环境时,它不可用.
View
is a native element, and is therefore not available to the Jasmine environment when you run it outside of a native environment.
这通常可以通过模拟整个react-native组件API来解决(例如,使用类似酶之类的浅呈现方法>.两者都可以与任何测试框架一起使用.
This is usually solve by either mocking the entire react-native component API (For example by using something like react-native-mock), or by using a shallow rendering approach such as Enzyme. Both will work with any testing framework.
那是说,在写了一些测试之后,我发现如果我重构代码以使函数中的所有逻辑都与本机无关,那么端到端测试将覆盖相互作用,那么组件级测试就变得多余了,几乎没有价值.
That said, After writing these kind of tests for a bit, I found that if I refactor the code to have all of the logic in functions that have nothing to do with react-native, and end-to-end tests cover the interaction, then the component-level tests become redundant and give very little value.
这篇关于使用Jasmine和TypeScript测试react-native时找不到模块'View'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!