在浏览器上对 Nativescript 应用程序逻辑进行单元测试 [英] Unit testing Nativescript application logic on a browser
问题描述
我正在尝试为 Nativescript 应用程序设置单元测试,由 ng test
在浏览器上运行.问题是每当有 tns-core-modules
或其他插件导入时,模块都无法解析,因为平台特定的文件(例如tns-core-modules/application/application.android.js") 永远不会被编译到包中,从而抛出类似找不到模块:错误:无法解析‘tns-core-modules/application’"这样的错误.
I am trying to set up unit testing for a Nativescript application, run by ng test
on a browser. The problem is that whenever there is a tns-core-modules
or another plugin import, the module cannot be resolved because of the platform specific files (e.g. "tns-core-modules/application/application.android.js") that never get compiled into the bundle, thus throwing an error like "Module not found: Error: Can't resolve 'tns-core-modules/application'".
我知道 Nativescript 有一个内置的单元测试支持.我遇到的问题是它不能在 CI 上运行.我希望能够对我的业务逻辑进行轻量级测试,模拟所有平台依赖项.我一直在寻找一种在运行时模拟模块导入的方法,但没有运气.我查看了 rewire
包,但它只在节点上运行.
I know there is a built-in unit test support in Nativescript. The problem I have with it is that it can't run on CI. I would like to be a ble to have lightweight tests for my business logic, mocking out all platform dependencies.
I have looked for a way to mock the module imports at runtime with no luck. I looked into rewire
package but it only runs on node.
推荐答案
我终于设法让它工作了.不是一个非常优雅的解决方案,我还没有看到它需要多少维护.这里的关键点:
I finally managed to get it working. Not a very elegant solution and I have yet to see how much maintenance it requires. Key points here:
- 使用
tsconfig.json
的paths
部分添加模拟导入地点 - 在 mocks 目录中为任何未解析的模块创建文件
- 一些 nativescript 模块在全局引用辅助函数范围,但它们未定义.我的解决方案是在
test.ts
像这样
- Use
paths
section of thetsconfig.json
to add mock import locations - In the mocks directory create files for any unresolved module
- Some nativescript modules are referencing helper functions on global
scope but they're undefined. My solution was to define them in
test.ts
like this
window['__decorate'] = () => {};
window['__extends'] = () => {};
window['__metadata'] = () => {};
window['__param'] = () => {};
window['layout_base_1'] = { CSSType: () => {} };
window['Crashlytics'] = {};
window['Fabric'] = {};
这篇关于在浏览器上对 Nativescript 应用程序逻辑进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!