【发布时间】:2019-05-03 09:12:35
【问题描述】:
React Context API 允许我将应用程序状态的逻辑放在一个地方(并避免使用 redux)。现在看起来是这样的
// Using the Context API used in react 16.3 - https://www.youtube.com/watch?v=XLJN4JfniH4
const { Provider, Consumer: ContextConsumer } = React.createContext()
class ContextProvider extends Component {
...// lot of functions ...
render() {
return (
<Provider
value={{
...this.state,
getDose: this.getDose,
getDoseRange: this.getDoseRange,
setDose: this.setDose,
checkIN: this.checkIN,
checkOUT: this.checkOUT,
getFalsifiedDrug: this.getDefaultproductData,
updatePrescriptionDose: this.updatePrescriptionDose,
}}
>
{this.props.children}
</Provider>
)
}
}
module.exports = { ContextConsumer, ContextProvider }
完整的代码可以在here找到。
构建 jest 测试的最佳实践是什么,让我可以测试功能并且不会弄乱状态?
(希望避免使用 Enzyme(由 AirBnB 开发)-因为AirBnB officially gave up using React Native)
示例
如何进行测试以确认当我调用 setDose(2) 时 productData.dose 已从 "5 mg" 更改为现在等于 "2 mg。但随后将状态设置回"5 mg" 以进行其他测试。
奖励信息
我无法让 jest 与我合作(因此我可以尝试建议的解决方案)
package.json
{
"main": "node_modules/expo/AppEntry.js",
"private": true,
"scripts": {
"test": "jest --watchAll"
},
"dependencies": {
"@expo/samples": "2.1.1",
"crypto-js": "^3.1.9-1",
"date-fns": "^1.29.0",
"expo": "^28.0.0",
"invert-color": "^1.2.3",
"lodash": "^4.17.10",
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-28.0.0.tar.gz",
"react-native-qrcode": "^0.2.6",
"react-native-slider": "^0.11.0",
"react-native-switch": "^1.5.0",
"react-navigation": "2.3.1",
"whatwg-fetch": "^2.0.4"
},
"devDependencies": {
"babel-eslint": "^10.0.1",
"babel-preset-expo": "^5.0.0",
"eslint": "^5.16.0",
"eslint-config-codingitwrong": "^0.1.4",
"eslint-plugin-import": "^2.17.2",
"eslint-plugin-jest": "^22.5.1",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.13.0",
"jest-expo": "^32.0.0",
"react-native-testing-library": "^1.7.0",
"react-test-renderer": "^16.8.6"
},
"jest": {
"preset": "jest-expo"
}
}
它只是把这个扔给我
> @ test /Users/norfeldt/Desktop/React-Native/MedBlockChain
> jest --watchAll
● Validation Error:
Module react-native/jest/hasteImpl.js in the haste.hasteImplModulePath option was not found.
<rootDir> is: /Users/norfeldt/Desktop/React-Native/MedBlockChain
Configuration Documentation:
https://jestjs.io/docs/configuration.html
npm ERR! Test failed. See above for more details.
我尝试过类似
rm -rf node_modules/ yarn.lock package-lock.json && npm install
【问题讨论】:
-
我想你可以使用:github.com/airbnb/enzyme,这个库提供了一个很好的API来测试状态等等。
-
谢谢,但 AirBnB 已经停止使用 React Native,所以我希望避免使用它,因为我希望它只针对 React (web)。
标签: javascript reactjs react-native jestjs