Turn your manual testers into automation experts Request a DemoStart testRigor Free

Meteor.js Testing

Meteor.js Testing

What is Meteor.js?

Meteor is a complete development tool and a JavaScript framework for developing modern web and mobile applications. It includes a key set of technologies for building connected-client reactive applications, a build tool, and a curated set of packages from the Node.js and general JavaScript community. The following are some of its features:
  • It allows development in a single language, JavaScript, in the application server, web browser, and mobile device.
  • It supports data on the wire, meaning that the server sends data, not HTML, and the client renders it.
  • It is also full stack reactive, which allows the UI to seamlessly capture the true state of the world with minimized development effort.

About Meteor.js testing

The Meteor framework covers the full stack—Meteor JavaScript code runs both on the client (a web browser or mobile application, typically) and the server (a Node.js process). Logical sections of code that should be tested together often span both sides of the client-server divide. Meteor provides a unique opportunity to address this challenge as it has been built from the ground up to run code on both sides of the stack. While other frameworks test to ensure that the server handles the publication and method combination correctly in isolation, with Meteor, an integration test can be built that crosses that boundary. It covers web stack testing and full app testing modes.

The types of testing that can be conducted include:

What is Unit testing?

Unit testing focuses on the smallest pieces of code that can be logically isolated in a system. In most programming languages, this can be a function, a subroutine, a method, or a property. The isolation part of the definition is important. We'll need to stub and mock other modules that our module usually leverages in order to isolate each test. We also need to spy on actions that the module takes to verify that they occur.

How to conduct Unit testing in Meteor.js?

The Meteor "test" command is used primarily to perform unit and simple integration tests for an application in Meteor.

What does "test mode" do?
  • Does not eagerly load any application code as Meteor normally would. Meteor wouldn't know of any methods/collections/publications unless you import them in your test files.
  • Does eagerly load any file in the application (including in imports/ folders) that look like .test[s]., or .spec[s].
  • Sets the Meteor.isTest flag to true.
  • Starts up the test driver package (Test driver package).

Other important configurations needed would be as below:

Mocha

Used as a test runner, Mocha is a JavaScript test framework running on Node.js and the browser, making asynchronous testing simple and adaptive. Mocha tests run serially, allowing for accurate and flexible reporting, while linking uncaught exceptions to the correct test cases.

Here's how you can add the meteortesting:mocha package to the app:
meteor add meteortesting:mocha

Chai

Chai is a BDD / TDD assertion library for Node and the browser that can be configured with any JavaScript testing framework like Mocha. It offers several interfaces that developers can choose from. BDD styles provide an expressive language & readable style, while TDD provides an assertive style.

Here are some example usages:
  • Expect: Enables the BDD style assertions and allows to include arbitrary messages to prepend to any failed assertions that might occur. Example: expect(answer, 'topic [answer]').to.equal(42);
  • Should: Allows for the same chainable assertions as the expect interface, but extends each object with a should property to start your chain. Example: beverages.should.have.property('tea').with.lengthOf(3);
  • Assert: Implemented through the assert interface, this module provides different additional tests and is also browser compatible. It allows you to include an optional message as the last parameter in the assert statement. These will be included in the error messages should the assertion not pass. Example: assert.typeOf(foo, 'string', 'foo is a string');

Test driver package

When running the Meteor test command, the --driver-package argument needs to be provided.

There are two types of reporters:
  • Web reporters: Meteor applications display a special test reporting web UI where you can view the test results.
  • Console reporters: These run completely on the command-line and are primarily used for automated testing like continuous integration.
Here's a sample code for unit testing in Meteor:
import { Meteor } from 'meteor/meteor';
    import expect from 'expect';
    import { Notes } from './notes';
     
    describe('notes', function () {
      const noteOne = {
        _id: 'testNote1',
        title: 'Groceries',
        body: 'Milk, Eggs and Oatmeal',
        userId: 'userId1'
      };
      
      it('should return a users notes', function () {
        const res = Meteor.server.publish_handlers['user.notes'].apply({ userId: noteOne.userId });
        const notes = res.fetch();
        expect(notes.length).toBe(1);
        expect(notes[0]).toEqual(noteOne);
      });
      
      it('should return no notes for user that has none', function () {
        const res = Meteor.server.publish_handlers.notes.apply({ userId: 'testid' });
        const notes = res.fetch();
        expect(notes.length).toBe(0);
      });
    });

In the above code, unit testing is conducted to test the Notes module in Meteor.server.publish_handlers. The describe() and it() functions are used, where describe(): acts as test suites and it(): acts as test cases.

Integration Testing

Integration testing evaluates the interoperability of software modules that interface across module boundaries. It's considered the second phase of the software testing process, following unit testing. Its main goal is to identify discrepancies between software modules that could lead to errors. Integration testing enables developers and testers to ensure each module can effectively communicate with the database. Given that modules frequently interact with third-party APIs or tools, integration testing is necessary to verify that the data these tools receive is precise and accurate.

How to conduct Integration testing in Meteor.js?

While conceptually distinct from unit tests, simple integration tests employ the same Meteor test mode and isolation techniques used for unit testing. An integration test that crosses the client-server boundary of a Meteor application requires a different testing infrastructure, known as Meteor's "full app" testing mode.

Generally, conducting an integration test involves the following steps:
  • Importing the relevant modules to be tested.
  • Stubbing, as the system under test in the integration test has a broader surface area, requires the stubbing of additional integration points with the rest of the stack.
  • Creating integration test data to execute the integration test scenarios.
Here is a sample code for simple integration tests:
import * as fetchModule from 'meteor/fetch';
import chai from 'chai';
import spies from 'chai-spies';
import fetchSomething from './fetch.something.js';

chai.use(spies);

const sandbox = chai.spy.sandbox();
const mockFetch = (mock) => {
  sandbox.on(fetchModule , 'fetch', mockFn);
}
describe('FetchSomething Testing', () => {
  if('simple mocking test', () => {
    mockFetch(() => console.log);
    fetchSomething('https://www.tryandfetch.com');
  });
});

The above example is an integration test module for fetchSomething (e.g., testing of correct headers or correct server errors).

End-to-end testing

End-to-end testing scrutinizes the complete software application workflow, from start to finish, evaluating all systems, components, and integrations involved. Its primary aim is to verify that the application functions as intended and meets user requirements.

How to conduct e2e testing in Meteor.js?

Cypress

Cypress is a JavaScript-based end-to-end testing tool designed for modern web test automation. This developer-friendly tool operates directly in the browser using a DOM manipulation technique, enabling front-end developers and QA engineers to write automated web tests.

Here is a sample end-to-end code using Cypress for Meteor.js testing:
describe("sign-up", () => {
  beforeEach(() => {
    cy.visit("http://localhost:3000/");
  });
  
  it("should create and log the new user", () => {
    cy.contains("Register").click();
    cy.get("input#at-field-email").type("exampleuser@gmail.com");
    cy.get("input#at-field-password").type("1password");
    cy.get("input#at-field-password_again").type("1password");
    cy.get("input#at-field-name").type("example-name");
    cy.get("button#at-btn").click();
    
    cy.url().should("eq", "http://localhost:3000/board");
    cy.window().then(win => {
      const user = win.Meteor.user();
      expect(user).to.exist;
      expect(user.profile.name).to.equal("example-name");
      expect(user.emails[0].address).to.equal("exampleuser@gmail.com");
    });
  });
});

testRigor

testRigor is an easy to use cloud-based end-to-end testing tool. It supports a range of platforms, including web and mobile browsers, native desktop, hybrid and native mobile applications, and APIs. testRigor is a codeless system, enabling you to write tests from scratch using plain English commands.

Equipped with AI and ML algorithms, testRigor provides up to 15x faster test creation and requires 200x less test maintenance compared to traditional methods. The tool integrates seamlessly with a wide array of other platforms, such as Jira, Zephyr, Oracle, PostgreSQL, as well as CI/CD tools like Jenkins, AWS, and GitLab. testRigor also offers a record-and-playback extension that can be used to record test cases and generate test scripts in plain English.

Here's an example of code using testRigor:
check that page contains "Register"
click on "Register"
enter stored value "exampleuser@gmail.com" in "Email" field
enter stored value "1password" in "Password" field
enter stored value "1password" in "Confirm Password" field
enter stored value "example-name" in "Name" field
click button "Submit"
open url "http://localhost:3000/board"
check that page contains "example-name"
check that page contains "exampleuser@gmail.com"

Conclusion

In Meteor.js development, there's no single type of testing that stands above all others. Instead, it's crucial to consider a range of testing methodologies to formulate the most effective strategy. The right testing approach can bring significant value to your project and ensure the delivery of high-quality applications to end users.