我刚刚开始使用Ionic 3开发我的第一个应用程序,现在正在进行一些单元测试。现在,当Service
是其依赖项之一时,我面临着“编译” Platform
的单元测试的问题。
这里是Service
的摘要:
@Injectable()
export class MyService {
constructor(public platform: Platform) {}
myMethod(): Observable<any> {
if (this.platform.is('android')) {
return new Observable(android);
else if (this.platform.is('ios')) {
return new Observable(iOS);
}
}
}
这是我根据互联网上的一些教程进行的单元测试:
describe('XXX', () => {
var service: MyService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [MyService, Platform]
});
});
it('should xxx', inject([MyService], (service) => {
var result = service.mymethod();
expect(result).toBeDefined();
}));
});
我的测试配置已按照此blog post进行。我还有其他spec
个文件可以成功运行,但该文件会引发以下错误:
PS C:\Workspaces\JS-TS\taccess> npm run test
> taccess@0.0.1 test C:\Workspaces\JS-TS\taccess
> karma start ./test-config/karma.conf.js --single-run
(node:17164) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
‼ 「wdm」:
i 「wdm」: Compiled with warnings.
i 「wdm」: Compiling...
‼ 「wdm」:
i 「wdm」: Compiled with warnings.
26 07 2018 07:20:43.963:INFO [karma]: Karma v2.0.5 server started at http://0.0.0.0:9876/
26 07 2018 07:20:44.003:INFO [launcher]: Launching browser Chrome with unlimited concurrency
26 07 2018 07:20:44.806:INFO [launcher]: Starting browser Chrome
26 07 2018 07:20:54.988:INFO [Chrome 68.0.3440 (Windows 10 0.0.0)]: Connected on socket u2KlYyff-qRa_fnHAAAA with id 6508927
Chrome 68.0.3440 (Windows 10 0.0.0) ERROR
{
"message": "An error was thrown in afterAll\nUncaught Error: Cannot find module './components/app/app-root'",
"str": "An error was thrown in afterAll\nUncaught Error: Cannot find module './components/app/app-root'"
}
Chrome 68.0.3440 (Windows 10 0.0.0) ERROR
{
"message": "An error was thrown in afterAll\nUncaught Error: Cannot find module './components/app/app-root'",
"str": "An error was thrown in afterAll\nUncaught Error: Cannot find module './components/app/app-root'"
}
Chrome 68.0.3440 (Windows 10 0.0.0): Executed 0 of 0 ERROR (0.008 secs / 0 secs)
Chrome 68.0.3440 (Windows 10 0.0.0): Executed 0 of 0 ERROR (0.142 secs / 0 secs)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! taccess@0.0.1 test: `karma start ./test-config/karma.conf.js --single-run`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the taccess@0.0.1 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xxx\AppData\Roaming\npm-cache\_logs\2018-07-26T05_20_56_762Z-debug.log
为什么我需要向服务中注入Platform
?因为我正在使用BLE的Cordova插件,所以iOS和Android之间存在一些我需要管理的差异。
有人对正在发生的事情有任何线索吗?我在做什么错了?
注释1 :我已经检查过使用Platform
删除依赖项,并且该测试(由于缺少Platform
而进行了一些修改)效果很好。
答案 0 :(得分:0)
一段时间后,我发现了问题所在:Visual Studio代码。
由于某些原因,VSCode更改了此导入
import { Platform } from 'ionic-angular';
与其他人
import { Platform } from 'ionic-angular/umd';
我一移除/umd
的一切,就像魅力一样。
希望这对以后的人有帮助。