meteor / validated-method

Meteor methods with better scoping, argument checking, and good defaults.
https://atmospherejs.com/mdg/validated-method
MIT License
194 stars 28 forks source link

Add `test` method that mocks environment, like unblock #11

Closed dan335 closed 3 years ago

dan335 commented 8 years ago
method = new ValidatedMethod({
  name: 'method',
  validate: null,
  run() {
    this.unblock();
  }
});

this works

method.call();

this

method._execute();

gives me this error

TypeError: Object [object global] has no method 'unblock'
stubailo commented 8 years ago

I think it might make sense to add a special function called test or something that automatically passes nice default stubs for things, and just isn't run when the Method is called for real.

The way it works now, _execute is the internal function that runs when the Method is actually called in the real app, so it probably wouldn't make sense to add functionality inside to pass fake versions of unblock and such.

dan335 commented 8 years ago

Sounds like a good idea to me.

stubailo commented 8 years ago

This could now be implemented via mixin:

https://github.com/meteor/validated-method#mixins

diavrank commented 3 years ago

Hello, I have the same problem here. Any suggestions to solve it?

filipenevola commented 3 years ago

Hi @diavrank did you try via mixin as suggested by Sashko?

diavrank commented 3 years ago

@filipenevola I read the section of mixins that Sashko shared, however, I have no idea which mixin I have to add, in order to solve the problem.

filipenevola commented 3 years ago

Hi @diavrank I didn't test but as far as I understand he means that you could create a mock unblock function using a mixin.

I'm writing the following code directly on GitHub so maybe it doesn't work :)

export const unblockMixin = options => {
  const { run } = options;

  return assign(options, {
    run(...args) {
      if (Meteor.isTest) {
        this.unblock = () => {}; // no-op
      }
      return run.call(this, ...args);
    },
  });
};

And you could use like this in your code:

new ValidatedMethod({
  name: 'yourMethod',
  mixins: [unblockMixin],
  validate: null, // your validation
  run(args) {
    this.unblock(); // It would always exists
    // your method body
  },
});

Let me know if this works.

diavrank commented 3 years ago

Thank you @filipenevola ,it did work. I used this code with TS:

unblockOnTest.ts

import { Meteor } from 'meteor/meteor';

export const unblockOnTest = (options: any) => {
    const { run } = options;

    return Object.assign(options, {
        run(...args: any[]) {
            if (Meteor.isTest || Meteor.isAppTest) {
                this.unblock = () => {
                }; // no-op
            }
            return run.call(this, ...args);
        }
    });
};