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

Testing Async Validators #1

Open
d1b1 opened this issue Sep 19, 2016 · 1 comment
Open

Testing Async Validators #1

d1b1 opened this issue Sep 19, 2016 · 1 comment

Comments

@d1b1
Copy link

d1b1 commented Sep 19, 2016

Hi, Great blog post and sample code. I am finding that when I stub a Schema Find and try to get the following I never get a response. I looks like the validator starts, but the find in the call does not resolve.

    it('should be invalid if emailkey is not unique', sinon.test(function() {
        var atpl = { emailKey: 'one', name: 'one' };
        this.stub(Template, 'find').yields(null, atpl );

        var m = new Template({ emailKey: 'one', name: ''});

        m.validate(function(err) {
            expect(err.errors.name).to.not.exist;
            done();
        });
    }));
schema.path('emailKey').validate(function (emailKey, fn) {

    // We allow empty phone numbers.
    if (!emailKey) return fn(true);

    // Check only when it is a new user or when phone_number field is modified
    if (this.isNew || this.isModified('emailKey')) {
        var Template = mongoose.model('Template');

        Template.find({ emailKey: emailKey }).exec(function (err, results) {
            fn(!err && results.length === 0);
        });
    } else fn(true);

}, 'Email Key already exists');
@jhartikainen
Copy link
Owner

One issue which I can see with that test is you're calling done in the validate callback, but you're not passing done as a parameter.

it('should be invalid if emailkey is not unique', sinon.test(function() {

This should be

it('should be invalid if emailkey is not unique', sinon.test(function(done) {

Note the done parameter in the function.

Since the parameter is missing, Mocha assumes this test is synchronous, so the error won't get reported correctly.

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

2 participants