问题
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...
In my configuration file (jasmine.json) I have:
{
"spec_dir": ".",
"spec_files": [
"src/*.spec.tsx"
],
"helpers": [
"./node_modules/ts-node/register.js"
]
}
My package.json
"react": "16.0.0-alpha.12",
"react-native": "0.45.1",
"jasmine": "^2.6.0",
"ts-node": "^3.3.0",
My test script on package.json
"test": "jasmine --config=jasmine.json"
My test
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:
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)
Any tests on my component fail because the "root" element it uses is a View
.
Why do I get this error? Is there any way I can use Jasmine to test instead of Jest?
回答1:
View
is a native element, and is therefore not available to the Jasmine environment when you run it outside of a native environment.
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.
来源:https://stackoverflow.com/questions/45717910/cannot-find-module-view-while-testing-react-native-with-jasmine-and-typescript