Mads L. Møller
Mads L. Møller

Reputation: 19

How would I test this method with JEST?

This is my first time trying JEST and I was wondering how I would write a test for my Length.convert() where I am accounting for "I" or different, but not specifically for "I" and "M". How would I test that specifically?

MY LENGTH CLASS

class Length {
  constructor(measure, system) {
    this.measure = measure;
    this.system = system;
  }

  convert() {
    if (this.system === "I") {
      return (this.measure * 2.54).toFixed(2);
    } else {
      return (this.measure * 0.393701).toFixed(2);
    }
  }
}

const firstLength = new Length(20, "I");
const secondLength = new Length(7, "M");

console.log(firstLength);
console.log(firstLength.convert());
console.log(secondLength);
console.log(secondLength.convert());

MY JEST TEST

const constructor = require("./length");
const convert = require("./length");

test("", () => {
  expect().toBe();
});

Upvotes: -1

Views: 151

Answers (1)

Svetoslav Petkov
Svetoslav Petkov

Reputation: 1575

I have assumed the ecmascript version base on the require("").

The working solution can be found here: Stack-blitz demo To prove it is working: just type nmp test in the stack-blitz console

Length class needs to be exported like this

Length.js

class Length {
  // The other code is omitted
}

module.exports = Length;

Only the constructor has to be imported. And in order to use it, you need to create an instance within the test

Length.test.js

const Length = require('./length.js');

test('Test Description', () => {
  //SETUP
  const length = new Length(1, 'I');

  //ACT
  const result = length.convert();

  //ASSERT
  expect(result).toBe('2.54');
});

Upvotes: 0

Related Questions