Node.js 如何测试硬件相关功能?
我正在编写一个Node.js应用程序,它使用外部设备,如打印机和智能卡读卡器 我正在尝试为使用这些设备的功能编写测试,我的最终目标是为我的项目设置CI。然而,我不知道是否有可能为此目的模拟硬件设备,或者是否有可能Node.js 如何测试硬件相关功能?,node.js,unit-testing,Node.js,Unit Testing,我正在编写一个Node.js应用程序,它使用外部设备,如打印机和智能卡读卡器 我正在尝试为使用这些设备的功能编写测试,我的最终目标是为我的项目设置CI。然而,我不知道是否有可能为此目的模拟硬件设备,或者是否有可能 如果这有帮助,我将模块用于智能卡读卡器,将模块用于打印机。通常,您需要模拟对所用模块的API调用 要在jasmine中给出使用节点打印机的示例,请执行以下操作: const printer = require('node-printer'); const myModule = requ
如果这有帮助,我将模块用于智能卡读卡器,将模块用于打印机。通常,您需要模拟对所用模块的API调用 要在
jasmine
中给出使用节点打印机的示例,请执行以下操作:
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等)中构造类似的示例。这取决于具体情况。通常,您需要模拟访问设备而不是设备本身的模块。您能提供测试套件的一般描述吗?例如,在jest中,您可以非常轻松地模拟整个模块,但通常在所有流行的测试框架中都可以进行模拟。