Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#785@minor: Add document.title. #786

Merged
merged 3 commits into from
Feb 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/happy-dom/src/nodes/document/Document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,34 @@ export default class Document extends Node implements IDocument {
return charset ? charset : 'UTF-8';
}

/**
* Returns title.
*
* @returns Title.
*/
public get title(): string {
const el = this.querySelector('title');
if (el) {
return el.textContent;
}
return '';
}

/**
* Returns set title.
*
*/
public set title(title: string) {
const el = this.querySelector('title');
if (el) {
el.textContent = title;
} else {
const titleEl = this.createElement('title');
titleEl.textContent = title;
this.head.appendChild(titleEl);
}
}

/**
* Last element child.
*
Expand Down
1 change: 1 addition & 0 deletions packages/happy-dom/src/nodes/document/IDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export default interface IDocument extends IParentNode {
readonly visibilityState: VisibilityStateEnum;
readonly hidden: boolean;
cookie: string;
title: string;

// Events
onreadystatechange: (event: Event) => void;
Expand Down
14 changes: 14 additions & 0 deletions packages/happy-dom/test/nodes/document/Document.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,20 @@ describe('Document', () => {
});
});

describe('get title() and set title()', () => {
it('Returns and sets title.', () => {
document.title = 'test title';
expect(document.title).toBe('test title');
const title = document.head.querySelector('title');
expect(title.textContent).toBe('test title');
document.title = 'new title';
expect(document.title).toBe('new title');
expect(title.textContent).toBe('new title');
title.textContent = 'new title 2';
expect(document.title).toBe('new title 2');
});
});

describe('get body()', () => {
it('Returns <body> element.', () => {
expect(document.body === document.children[0].children[1]).toBe(true);
Expand Down