【问题标题】:How do I test a method in a typescript?如何在打字稿中测试方法?
【发布时间】:2019-01-12 16:48:38
【问题描述】:

告诉我,我如何测试 distanceCalculation() 方法? 我想用精确指定的值检查测试结果的准确性。 如何在 Jest 中测试 Typescript 的方法? 这是一个测试任务,我只是在学习。

class Car {
  amountOfFuel: number;
  fuelСonsumption: number;

    constructor(carAmountOfFuel: number,
      carFuelСonsumption: number) {
        this.amountOfFuel = carAmountOfFuel;
        this.fuelСonsumption = carFuelСonsumption;
      }

      distanceСalculation(): number {
        return (this.amountOfFuel / this.fuelСonsumption)*100;
    }
}

export class Bentley extends Car {
  }

export class Zhiguli extends Car {
  }

测试代码

import { Bentley, Zhiguli } from './sum'

test("property check Bentley", () => {
  let car1 = new Bentley(90, 12);

  expect(car1).toHaveProperty('amountOfFuel',90);
  expect(car1).toHaveProperty('fuelСonsumption', 12);
});

test("property check Zhiguli", () => {
  let car2 = new Zhiguli(40, 10);

  expect(car2).toHaveProperty('amountOfFuel',40);
  expect(car2).toHaveProperty('fuelСonsumption', 10);
});

【问题讨论】:

  • 调用方法并检查返回值或者你到底有什么问题

标签: typescript unit-testing testing jestjs


【解决方案1】:

如果距离计算应该可以从类外部访问,请确保将其标记为公开。

您可以调用它并从测试中检查返回的值,如下所示:

test("Bentley", () => {
  const car1 = new Bentley(90, 12);

  expect(car1).toHaveProperty('amountOfFuel',90);
  expect(car1).toHaveProperty('fuelСonsumption', 12);

  expect(car1.distanceСalculation()).toBe(750);
});

test("Zhiguli", () => {
  const car2 = new Zhiguli(40, 10);

  expect(car2).toHaveProperty('amountOfFuel',40);
  expect(car2).toHaveProperty('fuelСonsumption', 10);

  expect(car2.distanceСalculation()).toBe(400);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 2018-08-24
    • 2023-04-09
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多