You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jasmine测试中验证函数是否调用了另一个函数?

Fixing the Jasmine Test for Person.getName()

First, let's fix the test case to properly verify that getName() calls getFullName(). Here's the corrected code with explanations:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  getName() {
    this.getFullName(); // Added semicolon for consistency
  }
  getFullName() {
    return this.firstName + this.lastName; // Fixed: added return statement (original had no return)
  }
}

describe('Test Person', () => {
  let programmer; // Declare variable outside beforeEach to access it in the test block

  beforeEach(() => {
    programmer = new Person('John', 'Gray');
    spyOn(programmer, 'getFullName'); // Spy on the getFullName method
    programmer.getName(); // Trigger the method we want to test
  });

  it('getName should call getFullName', () => {
    // Verify the spy was called at least once
    expect(programmer.getFullName).toHaveBeenCalled();
    
    // Optional: Verify it was called exactly once (more precise)
    // expect(programmer.getFullName).toHaveBeenCalledTimes(1);
  });
});

Key Fixes & Explanations:

  • Fixed variable scope: Originally, programmer was declared as a const inside beforeEach, which made it inaccessible in the test (it) block. Moving the declaration outside lets the test access the spy.
  • Completed the expect statement: Used Jasmine's toHaveBeenCalled() matcher to confirm the spy was invoked. For stricter checks, toHaveBeenCalledTimes(1) ensures the method was called exactly once.
  • Minor class improvements: Added a return statement to getFullName() (since the original code didn't return anything, which is likely unintended) and cleaned up syntax for consistency.

How the Test Works:

  1. We set up a spy on getFullName to track when it's called.
  2. We run getName(), which should trigger getFullName().
  3. The test checks if the spy was activated, confirming the interaction between the two methods.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:07:29