how to mock/stub a node.js module

2019-08-20 05:25发布

问题:

I'm working on some code to run on RaspberryPi, and I'm using the Wiring-Pi node module. I have two problems

1) Wiring-Pi won't build on x86 platforms

2) Node-jasmine won't build on RaspberryPi

So, after playing around with a bunch of different ideas, I'm wondering if I'm best off to mock or stub the Wiring-Pi module when on x86 platforms, so I can run the tests.

Of course, my problem is that the file I'm testing includes the require statment

    // getters.js
    var wpi = require('wiring-pi');

    // getters.spec.js
   var get = require('../lib/getters.js');

Is there a way I can set-up the spec file so that the getters.js file doesn't load the wiring-pi module?

回答1:

You can use this to control loading of the wiring-pi module:

var wpi = require('os').arch() === 'arm' ? require('wiring-pi') : {};

Jasmine compiles, installs and runs on the Pi. What error do you get?