导出/导入类以测试其方法和构造函数

问题描述 投票:0回答:1

我一直不知道如何测试课程。

ship.js

class Ship {
    /**
     * Constructor for setting up a ship object
     * @param {Number} length length of the ship
     * @param {Number} hits how many times the ship has been hit
     * @param {Boolean} isSunk If the ship is sunk
     */
    constructor(length, hits = 0, isSunk = false) {
        this.length = length;
        this.hits = hits;
        this.isSunk = isSunk;
    }

    /**
     * When a ship is hit by a player, or computer, increase it's hit count.
     */
    hit() {
        this.hits += 1;
    }

    /**
     * If the length of the ship is equal to the number of hits, the ship is sunk.
     */
    checkHitsToSink() {
        this.length === this.hits ? (this.isSunk = true) : null;
    }
}

/**
 * Exporting for unit testing
 */
module.exports = Ship;

tests/ship.test.js

const Ship = require('../ship');

test('ship should be {length: 3, hits: 2, isSunk: false}', () => {
    const ship = new Ship(3, 2, false);
    require(ship).toHaveProperty('length', 3);
});

当我尝试运行此测试时,会输出

TypeError: moduleName.startsWith is not a function

PS C:\Users\brand\Desktop\github\Battleship> npm test

> [email protected] test
> jest

 FAIL  src/tests/ship.test.js
  × ship should be {length: 3, hits: 2, sunk: false} (2 ms)

  ● ship should be {length: 3, hits: 2, sunk: false}

    TypeError: moduleName.startsWith is not a function

      3 | test('ship should be {length: 3, hits: 2, sunk: false}', () => {
      4 |       const ship = new Ship(3, 2, false);
    > 5 |       require(ship).toHaveProperty(length, 3);
        |       ^
      6 | });
      7 |

      at Resolver.isCoreModule (node_modules/jest-resolve/build/resolver.js:452:20)
      at Object.require (src/tests/ship.test.js:5:2)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.707 s, estimated 1 s
Ran all test suites.

有没有一种方法可以像这样测试一个类,或者是否有完全不同的方法来测试类?

我尝试了多种方法来测试此类(例如使用 ESM import/export 语句、尝试将构造函数或类的方法直接传递到

module.exports
以及其他一些方法),但我遇到了 TypeErrors、ReferenceErrors和语法错误。

javascript webpack jestjs babel-jest
1个回答
0
投票

有正确的版本:

const Ship = require('../ship');

test('ship should be {length: 3, hits: 2, isSunk: false}', () => {
    const ship = new Ship(3, 2, false);
    expect(ship).toHaveProperty('length', 3);
});

错误是由于您在测试主体中使用 require 而不是 expect 导致的。

© www.soinside.com 2019 - 2024. All rights reserved.