From 5e19bc36a80c4bb8663449e4652f4448d6a8a54d Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Fri, 24 Feb 2023 14:44:08 +0800 Subject: [PATCH] #785@minor: Add document.title. --- .../happy-dom/src/nodes/document/Document.ts | 28 +++++++++++++++++++ .../happy-dom/src/nodes/document/IDocument.ts | 1 + .../test/nodes/document/Document.test.ts | 14 ++++++++++ 3 files changed, 43 insertions(+) diff --git a/packages/happy-dom/src/nodes/document/Document.ts b/packages/happy-dom/src/nodes/document/Document.ts index b7738ebe0..2122ee999 100644 --- a/packages/happy-dom/src/nodes/document/Document.ts +++ b/packages/happy-dom/src/nodes/document/Document.ts @@ -226,6 +226,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. * diff --git a/packages/happy-dom/src/nodes/document/IDocument.ts b/packages/happy-dom/src/nodes/document/IDocument.ts index 6e31e9ad9..18dd36150 100644 --- a/packages/happy-dom/src/nodes/document/IDocument.ts +++ b/packages/happy-dom/src/nodes/document/IDocument.ts @@ -42,6 +42,7 @@ export default interface IDocument extends IParentNode { readonly URL: string; readonly documentURI: string; cookie: string; + title: string; // Events onreadystatechange: (event: Event) => void; diff --git a/packages/happy-dom/test/nodes/document/Document.test.ts b/packages/happy-dom/test/nodes/document/Document.test.ts index ce9730d17..d1509e410 100644 --- a/packages/happy-dom/test/nodes/document/Document.test.ts +++ b/packages/happy-dom/test/nodes/document/Document.test.ts @@ -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 element.', () => { expect(document.body === document.children[0].children[1]).toBe(true);