Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub/mock process.platform sinon

I am working with process.platform and want to stub that string value to fake different OSes.

(this object is generated out of my reach, and I need to test against different values it can take on)

Is it possible to stub/fake this value?

I have tried the following without any luck:

stub = sinon.stub(process, "platform").returns("something")

I get the error TypeError: Attempted to wrap string property platform as function

The same thing happens if I try to use a mock like this:

mock = sinon.mock(process);
mock.expects("platform").returns("something");
like image 264
Automatico Avatar asked Jun 07 '15 02:06

Automatico


People also ask

What is Sinon stub ()?

The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called. For example, the below code stubs out axios.

How do you mock a method in Sinon?

var mock = sinon. Creates a mock for the provided object. Does not change the object, but returns a mock object to set expectations on the object's methods.

What is Sinon used for?

Sinon JS is a popular JavaScript library that lets you replace complicated parts of your code that are hard to test for “placeholders,” so you can keep your unit tests fast and deterministic, as they should be.

How do you use Sinon in typescript?

In Typescript this can be achieved by using sinon. createStubInstance and SinonStubbedInstance class. Example: let documentRepository: SinonStubbedInstance<DocumentRepository>; documentRepository = sinon.


2 Answers

You don't need Sinon to accomplish what you need. Although the process.platform process is not writable, it is configurable. So, you can temporarily redefine it and simply restore it when you're done testing.

Here's how I would do it:

var assert = require('assert');

describe('changing process.platform', function() {
  before(function() {
    // save original process.platform
    this.originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');

    // redefine process.platform
    Object.defineProperty(process, 'platform', {
      value: 'any-platform'
    });
  });

  after(function() {
    // restore original process.platfork
    Object.defineProperty(process, 'platform', this.originalPlatform);
  });

  it('should have any-platform', function() {
    assert.equal(process.platform, 'any-platform');
  });
});
like image 133
JME Avatar answered Oct 26 '22 15:10

JME


sinon's stub supports a "value" function to set the new value for a stub now:

sinon.stub(process, 'platform').value('ANOTHER_OS');
...
sinon.restore() // when you finish the mocking

For details please check from https://sinonjs.org/releases/latest/stubs/

like image 40
Ron Wang Avatar answered Oct 26 '22 15:10

Ron Wang