首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试依赖于硬件的函数?

问如何测试依赖于硬件的函数?
EN

Stack Overflow用户
提问于 2018-12-28 20:35:01
回答 1查看 73关注 0票数 0

我正在编写一个使用外部设备的Node.js应用程序,比如打印机和智能卡阅读器。

我正在尝试为使用这些设备的功能编写测试,我的最终目标是为我的项目设置CI。但是,我不知道是否可以为此目的模拟硬件设备,或者根本不可能。

如果这有帮助,我对智能卡读卡器使用graphene模块,对打印机使用node-printer模块。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-28 23:15:57

通常,您应该模拟对您使用的模块的API调用。

在jasmine中给出使用node-printer的示例

代码语言:javascript
复制
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等)中构建类似的示例。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53958721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档