Angular 10单元测试中无法访问DIV子节点的问题及测试需求咨询
Let's break down what's going wrong and how to adjust your test cases to verify the child elements and their content properly.
1. Fix the SpyOn Syntax
First off, your spyOn call has a critical syntax error—you shouldn't include parentheses in the method name string. This mistake means your someCondition() method isn't being mocked correctly, which is likely preventing the <div> from rendering at all.
Incorrect:
spyOn(component, 'someCondition()').and.returnValue(true);
Correct:
spyOn(component, 'someCondition').and.returnValue(true);
2. Query Child <p> Elements Correctly
Your current code is targeting the <div> itself, not its child <p> tags. To access the 7 paragraph elements, you need to adjust your selector to target them directly, or first retrieve the div and then query its children.
Option 1: Directly Query All <p> Tags Inside the Div
Use the CSS selector #myID p to get all paragraph elements within the target div:
it('should check for 7 elements and verify content', async () => { // Mock the condition to ensure the div renders spyOn(component, 'someCondition').and.returnValue(true); fixture.detectChanges(); await fixture.whenRenderingDone(); // Get all <p> tags inside the #myID div const pElements = fixture.debugElement.queryAll(By.css('#myID p')); // Verify there are exactly 7 paragraph elements expect(pElements.length).toBe(7); // Verify specific paragraph content (example checks for first and last lines) expect(pElements[0].nativeElement.textContent.trim()).toBe('Line 1'); expect(pElements[6].nativeElement.textContent.trim()).toBe('Line 7'); });
Option 2: Retrieve the Div First, Then Check Its Children
If you want to first confirm the div exists before checking its children:
it('should check for 7 elements and verify content', async () => { spyOn(component, 'someCondition').and.returnValue(true); fixture.detectChanges(); await fixture.whenRenderingDone(); // Confirm the div is rendered const myDiv = fixture.debugElement.query(By.css('#myID')); expect(myDiv).toBeTruthy(); // Get all <p> children of the div const pElements = myDiv.queryAll(By.css('p')); expect(pElements.length).toBe(7); // Check content of a specific middle paragraph expect(pElements[3].nativeElement.textContent.trim()).toBe('Line 4'); });
3. Key Notes
- Always use
trim()ontextContentto avoid issues with extra whitespace in your template. - If your component relies on async operations (like data fetching), you might need to use
fakeAsyncandtick()instead ofasync/await, but for simple template conditions,await fixture.whenRenderingDone()works perfectly. - Double-check your test setup to ensure you've properly initialized the component (e.g., calling
fixture = TestBed.createComponent(YourComponent);andcomponent = fixture.componentInstance;).
Content of the question originates from Stack Exchange, asked by Arup Bhattacharya

