如何测试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') andassert.sctrictEqual(extra 'c' in "strict") which will cause errors before the test even runs. - Missing
newkeyword: When creating a Command instance, you need to usenew Command(...)—class constructors require thenewkeyword to instantiate an object. - Incorrect assertion target: You're comparing the entire Command instance to a string, but you should be checking the
commandTypeproperty 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
Commandusing thenewkeyword, passing in a specific command type string and value. - We then verify that the constructor correctly assigns the input value to the
commandTypeproperty of the instance usingassert.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




