Unit testing Meteor.methods with mocha/chai

I am currently stuck with an issue I am unable to resolve by myself or with the help of existing topic or internet results.

I am working on a project using React and Typescript.

I am trying to unit test Meteor.methods which are called from the client with Meteor.call(’…’).
I would say I am trying with mocha but now I am ready to try something else if it can help.

My test file defined in tests/main.ts

import { Meteor } from 'meteor/meteor';
import { expect } from 'chai';

describe("simple-method-testing", function () {
  if (Meteor.isClient) {
    it("client is not server", function () {
      assert.strictEqual(Meteor.isServer, false);
    });
  }

  if (Meteor.isServer) {
    it("1mytest", function (done) {
      Meteor.call('testForTest', true, (error, res)=>{
        if (error) done(error);
        else {
          expect(res).to.be.true;
          done();
        }
      })
    });
  }
});

I also tried doing in expect(Meteor.call(’’)) as I thought we could call it synchronously on the server.

my method defined in server/main.ts

Meteor.methods({
  
  testForTest: function(testBool:boolean): boolean{
    console.log("in testing");
    return testBool;
  },

And of course the issue: Error: Method ‘testForTest’ not found [404]

After doing some research I stumble across few solutions:
1: Meteor.server.methods_handler: Doesn’t work as Meteor.server is undefined.
2: Define my function outside of methods and do ‘testForTest’: testForTest. As I will work great with this function this is not a suitable solution for others where I will need Meteor.user() for example.

What is the correct and up to date way of doing methods unit testing ?
Thank you for your support and advice,
Thomas

What’s wrong with wrapping your test cases within Meteor.isServer? I’m using it like this and it works like a charm:

1 Like

Hello, thank you for your answer and your code example.
I have not issue using Meteor.isServer but I do with Meteor.server.method_handlers.

EDIT: Solve my issue, this was not Meteor.server has typescript was hinting to me but method_handler as I was not importing my methods.

Thank you very much!!

Did you manage to get rid of the TypeScript error?

PS: I managed. See patients/patients.merge.tests.ts at 02338ff02438bb4add511dcbb83eddc0c8fc2ee4 · infoderm/patients · GitHub