Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewire and Classes + Constructors + Prototypes #41

Closed
basdag opened this issue Feb 23, 2015 · 2 comments
Closed

Rewire and Classes + Constructors + Prototypes #41

basdag opened this issue Feb 23, 2015 · 2 comments

Comments

@basdag
Copy link

basdag commented Feb 23, 2015

Hello everyone,

First I would like to thanks in advance for any help or guidance that could be provided. I am new with rewire and I wanted to mock up a class with a constructor and several prototypes. A really trivial example of what I am trying to do, is to mock User Class in the code bellow, I would appreciate any guidance.


User Class
function User(name) {
    this.name = name;
}

User.prototype.getName = function getName() {
    return this.name;
};

module.exports = User;

Company Module
var user = require('user');

var users = [];

exports.setUser = function setUser(firstName, lastName) {
    users.push(new User(firstName + lastName));
}

exports.getUser = function getUser(id) {
    return users[id].getName();
}

Test Module
var company = rewire('./company');

// Here is were I would need to mock the User class.
var userMock = {
    .... // How to set the User constructor?
    .... // Prototypes follow the same pattern as exports?
    getName: function getName() {
         // Testing code behavior with empty results for example
         return null;
    }
}

company.__set__('user', userMock);

Thanks in advance for your time and support

@basdag basdag changed the title Rewire and Classes Constructors Rewire and Classes + Constructors + Prototypes Feb 23, 2015
@basdag basdag closed this as completed Feb 23, 2015
@ameykpatil
Copy link

@basdag How did you solve it? How do you mock constructors & protoypes using rewire? Any reference or link would be appreciated.

@jhnns
Copy link
Owner

jhnns commented May 15, 2015

@ameykpatil There should be no limitation. You can rewire just every variable. So in this case you just need to re-define the user variable with your mock:

function UserMock() {}

// Put your prototype methods here

company.__set__('user', UserMock);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants