如何在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,
programmerwas declared as aconstinsidebeforeEach, 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:
- We set up a spy on
getFullNameto track when it's called. - We run
getName(), which should triggergetFullName(). - The test checks if the spy was activated, confirming the interaction between the two methods.
内容的提问来源于stack exchange,提问作者darKnight
相关产品推荐
相关产品推荐

