我正在编写一个使用外部设备的Node.js应用程序,比如打印机和智能卡阅读器。
我正在尝试为使用这些设备的功能编写测试,我的最终目标是为我的项目设置CI。但是,我不知道是否可以为此目的模拟硬件设备,或者根本不可能。
如果这有帮助,我对智能卡读卡器使用graphene模块,对打印机使用node-printer模块。
发布于 2018-12-28 23:15:57
通常,您应该模拟对您使用的模块的API调用。
在jasmine中给出使用node-printer的示例
const printer = require('node-printer');
const myModule = require('module i am testing');
describe('printSomething', function () {
it('prints something and resolves when it completes', function (done) {
// Mock the printDirect method on node-printer, to immediately
// call the success callback. You might need to mock additional
// methods if you make multiple API calls in one method.
spyOn(printer, 'printDirect').andCallFake(options => {
options.success(12345);
});
myModule.printSomething('blah').then(result => {
// To be sure your module is calling the module with the expected
// arguments, you can check the actual arguments passed.
expect(printer.printDirect.calls.allArgs()).toEqual([[{
data: 'the exact data',
printer: 'PRINTERNAME',
success: jasmine.any(Function)
}]]);
done();
}).catch(done.fail);
});
});您可以在几乎任何测试框架(jest、mocha+sinon等)中构建类似的示例。
https://stackoverflow.com/questions/53958721
复制相似问题