You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何测试Command类构造函数正确设置commandType属性

Testing the Command Class Constructor's commandType Property

Let's fix your second test step by step. First, let's break down the issues in your current test code:

  • Spelling mistakes: You have contructorCheck (missing an 's') and assert.sctrictEqual (extra 'c' in "strict") which will cause errors before the test even runs.
  • Missing new keyword: When creating a Command instance, you need to use new Command(...)—class constructors require the new keyword to instantiate an object.
  • Incorrect assertion target: You're comparing the entire Command instance to a string, but you should be checking the commandType property of the instance instead.

Here's the corrected version of your test suite, with clear explanations:

const assert = require('assert');
const Command = require('../command.js');

describe("Command class", function() {
  it("throws error if command type is NOT passed into constructor as the first parameter", function() {
    assert.throws(
      function() { new Command(); },
      { message: 'Command type required.' }
    );
  });

  it("constructor should set command type", function(){
    // 1. Define a concrete test command type (use a string instead of an undefined variable)
    const testCommandType = 'MOVE';
    // 2. Create a valid Command instance with our test type and a sample value
    const commandInstance = new Command(testCommandType, 7);
    // 3. Assert the instance's commandType property matches our test value
    assert.strictEqual(commandInstance.commandType, testCommandType);
  });
});

Why this works:

  • We create a proper instance of Command using the new keyword, passing in a specific command type string and value.
  • We then verify that the constructor correctly assigns the input value to the commandType property of the instance using assert.strictEqual—this directly checks the behavior you're trying to validate.

Your original Command class already correctly sets this.commandType = commandType, so once the test is fixed, it should pass successfully.

内容的提问来源于stack exchange,提问作者Katie

火山引擎 最新活动