我是新来测试的.在测试期间,似乎无法让我的spec文件调用我的服务依赖项的模拟版本.相反,它调用原始的,这是不工作的,因为它是一个API,只运行在一个本地设备上.
正在测试的服务功能:
async startScan(): Promise<string | boolean> {
BarcodeScanner.hideBackground(); // make background of WebView transparent
try {
const result = await BarcodeScanner.startScan();
if (result.hasContent) {
console.log(result.content);
return result.content;
}
return false;
} catch (error) {
console.log("could not activate scanner. Are you on a mobile device?", error);
return false;
}
};
我的模拟条形码 scanner 服务:
export const BarcodeScanner = {
startScan: (options?: ScanOptions): Promise<ScanResult> => Promise.resolve({
hasContent: true,
content: 'mockContent',
format: 'mockFormat'
}),
}
我的spec文件:
import { ScannerService } from './scanner.service';
import { BarcodeScanner } from '../__mocks__/@capacitor/barcode-scanner';
describe('ScannerService', () => {
let scannerService: ScannerService
let barcodeScannerSpy: any
let capacitorCoreSpy: any;
beforeEach(() => {
barcodeScannerSpy = jasmine.createSpyObj('BarcodeScanner', ['hideBackground',
'showBackground',
'stopScan',
'checkPermissions',
'openAppSettings',
'checkPermission']);
capacitorCoreSpy = jasmine.createSpyObj('Capacitor', ['isNativePlatform']);
TestBed.configureTestingModule({
providers: [
ScannerService,
{ provide: BarcodeScanner, useValue: barcodeScannerSpy },
{ provide: Capacitor, useValue: capacitorCoreSpy }
]
});
scannerService = TestBed.inject(ScannerService) as jasmine.SpyObj<ScannerService>;
capacitorCoreSpy.isNativePlatform.and.returnValue(true);
});
it('should start scan', fakeAsync(() => {
let result: any;
scannerService.startScan().then(res => {
console.log("res", res);
result = res
});
expect(result).toEqual('mockContent');
}));
});
结果:
ScannerService > should start scan
Expected undefined to equal 'mockContent'.
这将返回FALSE,因为它由于调用了在Web浏览器中不起作用的原件而遇到了捕获错误的情况.
我怎么才能把这个叫假间谍?谢谢,感谢你的帮助.