Jsdom: O jsdom oferece suporte a elementos de vídeo e áudio?

Criado em 19 fev. 2018  ·  14Comentários  ·  Fonte: jsdom/jsdom

Informação básica:

  • Versão Node.js: 8.94
  • versão jsdom: 11.6.2

Em formação

Eu quero executar testes de unidade (usando ava e browser-env ) para um carregador de ativos que suporta pré-carregamento de imagem, áudio e vídeo. Eu queria saber se jsdom suporta elementos de áudio e vídeo. Quando tento criar e chamar video.load() em um elemento de vídeo ( HTMLVideoElement que é HTMLMediaElement ), jsdom retorna este erro:

Error: Not implemented: HTMLMediaElement.prototype.load

Presumo que não haja suporte para elementos de vídeo e áudio. Não encontrei nada sobre suporte de vídeo e áudio no jsdom, talvez esteja faltando?

Comentários muito úteis

jsdom não oferece suporte a nenhuma operação de carregamento ou reprodução de mídia. Como alternativa, você pode adicionar alguns stubs na configuração do teste:

window.HTMLMediaElement.prototype.load = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.play = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.pause = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.addTextTrack = () => { /* do nothing */ };

Todos 14 comentários

jsdom não oferece suporte a nenhuma operação de carregamento ou reprodução de mídia. Como alternativa, você pode adicionar alguns stubs na configuração do teste:

window.HTMLMediaElement.prototype.load = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.play = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.pause = () => { /* do nothing */ };
window.HTMLMediaElement.prototype.addTextTrack = () => { /* do nothing */ };

É disso que preciso aqui: uma maneira de simular o carregamento / busca de HTMLMediaElements . Ao fazer isso, ele não pré-carregará áudio e vídeo como em um navegador real, certo?

Normalmente, nenhuma busca é necessária para esses testes. Esses stubs suprimem as exceções jsdom, e então você poderá testar sua lógica com eventos despachados manualmente do elemento de vídeo (por exemplo, videoElement.dispatchEvent(new window.Event("loading")); ).

Tudo bem, obrigado pela ajuda, finalmente consertei meus testes. 👍

Isso me ajudou a começar, mas, no meu caso, quero testar se certas condições estão afetando corretamente a reprodução. Fiz a substituição de play e pause funções e tento definir a variável paused do elemento de mídia, mas recebo um erro de que há apenas um getter para essa variável. Isso torna a zombaria um pouco desafiadora.

Sou um pouco novo em JS. Existe uma maneira de simular variáveis ​​somente leitura como esta?

@BenBergman Você poderia fazer:

Object.defineProperty(HTMLMediaElement.prototype, "paused", {
  get() {
    // Your own getter, where `this` refers to the HTMLMediaElement.
  }
});

Excelente, obrigado! Para a posteridade, meu getter se parece com este para contabilizar um valor padrão:

get() {
    if (this.mockPaused === undefined) {
        return true;
    }
    return this.mockPaused;
}

Você pode simplificar ainda mais desta forma:

Object.defineProperty(mediaTag, "paused", {
  writable: true,
  value: true,
});

e então apenas altere mediaTag.paused = true ou mediaTag.paused = false em seu teste.

O benefício dessa abordagem é que é seguro para tipos, caso você esteja usando o TypeScript. Você não deve definir sua propriedade simulada de alguma forma como (mediaTag as any).mockPaused = true .

Melhor ainda, obrigado!

Como posso simular a reprodução do vídeo?
Eu criei play and load, mas não tenho ideia de como fazer o vídeo começar a ser reproduzido (ou acho que está tocando, tudo que preciso é o que acontece depois).
Object.defineProperty(HTMLMediaElement.prototype, "play", { get() { document.getElementsByTagName('video')[0].dispatchEvent(new Event('play')); } });

jsdom não oferece suporte a nenhuma operação de carregamento ou reprodução de mídia. Como alternativa, você pode adicionar alguns stubs na configuração do teste:

Obrigado pela solução alternativa. Posso perguntar por que isso não é compatível por padrão, no entanto?

Ninguém implementou um reprodutor de vídeo ou áudio no jsdom ainda.

Aqui está uma implementação rápida e suja (por brincadeira e vue) dos métodos play e pause que também envia alguns dos eventos que eu precisava para um teste ( loadedmetadata , play , pause ):

// Jest's setup file, setup.js

// Mock data and helper methods
global.window.HTMLMediaElement.prototype._mock = {
  paused: true,
  duration: NaN,
  _loaded: false,
   // Emulates the audio file loading
  _load: function audioInit(audio) {
    // Note: we could actually load the file from this.src and get real duration
    // and other metadata.
    // See for example: https://github.com/59naga/mock-audio-element/blob/master/src/index.js
    // For now, the 'duration' and other metadata has to be set manually in test code.
    audio.dispatchEvent(new Event('loadedmetadata'))
    audio.dispatchEvent(new Event('canplaythrough'))
  },
  // Reset audio object mock data to the initial state
  _resetMock: function resetMock(audio) {
    audio._mock = Object.assign(
      {},
      global.window.HTMLMediaElement.prototype._mock,
    )
  },
}

// Get "paused" value, it is automatically set to true / false when we play / pause the audio.
Object.defineProperty(global.window.HTMLMediaElement.prototype, 'paused', {
  get() {
    return this._mock.paused
  },
})

// Get and set audio duration
Object.defineProperty(global.window.HTMLMediaElement.prototype, 'duration', {
  get() {
    return this._mock.duration
  },
  set(value) {
    // Reset the mock state to initial (paused) when we set the duration.
    this._mock._resetMock(this)
    this._mock.duration = value
  },
})

// Start the playback.
global.window.HTMLMediaElement.prototype.play = function playMock() {
  if (!this._mock._loaded) {
    // emulate the audio file load and metadata initialization
    this._mock._load(this)
  }
  this._mock.paused = false
  this.dispatchEvent(new Event('play'))
  // Note: we could
}

// Pause the playback
global.window.HTMLMediaElement.prototype.pause = function pauseMock() {
  this._mock.paused = true
  this.dispatchEvent(new Event('pause'))
}

E o exemplo do teste (note que temos que definir manualmente audio.duration :

  // Test
  it('creates audio player', async () => {
    // `page` is a wrapper for a page being tested, created in beforeEach
    let player = page.player()

    // Useful to see which properties are defined where.
    // console.log(Object.getOwnPropertyDescriptors(HTMLMediaElement.prototype))
    // console.log(Object.getOwnPropertyDescriptors(HTMLMediaElement))
    // console.log(Object.getOwnPropertyDescriptors(audio))

    let audio = player.find('audio').element as HTMLAudioElement

    let audioEventReceived = false
    audio.addEventListener('play', () => {
      audioEventReceived = true
    })

    // @ts-ignore: error TS2540: Cannot assign to 'duration' because it is a read-only property.
    audio.duration = 300

    expect(audio.paused).toBe(true)
    expect(audio.duration).toBe(300)
    expect(audio.currentTime).toBe(0)

    audio.play()
    audio.currentTime += 30

    expect(audioEventReceived).toBe(true)

    expect(audio.paused).toBe(false)
    expect(audio.duration).toBe(300)
    expect(audio.currentTime).toBe(30.02)
  })

Considerei usar essas soluções alternativas, mas em vez de reimplementar um navegador como recursos de jogo, decidi usar puppeteer , ou seja, obter um navegador real para fazer o teste. Esta é a minha configuração:

src / reviewer.tests.ts

jest.disableAutomock()
// Use this in a test to pause its execution, allowing you to open the chrome console
// and while keeping the express server running: chrome://inspect/#devices
// jest.setTimeout(2000000000);
// debugger; await new Promise(function(resolve) {});

test('renders test site', async function() {
    let self: any = global;
    let page = self.page;
    let address = process.env.SERVER_ADDRESS;
    console.log(`The server address is '${address}'.`);
    await page.goto(`${address}/single_audio_file.html`);
    await page.waitForSelector('[data-attibute]');

    let is_paused = await page.evaluate(() => {
        let audio = document.getElementById('silence1.mp3') as HTMLAudioElement;
        return audio.paused;
    });
    expect(is_paused).toEqual(true);
});

testfiles / single_audio_file.html

<html>
    <head>
        <title>main webview</title>
        <script src="importsomething.js"></script>
    </head>
    <body>
    <div id="qa">
        <audio id="silence1.mp3" src="silence1.mp3" data-attibute="some" controls></audio>
        <script type="text/javascript">
            // doSomething();
        </script>
    </div>
    </body>
</html>

** globalTeardown.js **

module.exports = async () => {
    global.server.close();
};
** globalSetup.js **
const express = require('express');

module.exports = async () => {
    let server;
    const app = express();

    await new Promise(function(resolve) {
        server = app.listen(0, "127.0.0.1", function() {
            let address = server.address();
            process.env.SERVER_ADDRESS = `http://${address.address}:${address.port}`;
            console.log(`Running static file server on '${process.env.SERVER_ADDRESS}'...`);
            resolve();
        });
    });

    global.server = server;
    app.get('/favicon.ico', (req, res) => res.sendStatus(200));
    app.use(express.static('./testfiles'));
};
** testEnvironment.js **
const puppeteer = require('puppeteer');

// const TestEnvironment = require('jest-environment-node'); // for server node apps
const TestEnvironment = require('jest-environment-jsdom'); // for browser js apps

class ExpressEnvironment extends TestEnvironment {
    constructor(config, context) {
        let cloneconfig = Object.assign({}, config);
        cloneconfig.testURL = process.env.SERVER_ADDRESS;
        super(cloneconfig, context);
    }

    async setup() {
        await super.setup();
        let browser = await puppeteer.launch({
            // headless: false, // show the Chrome window
            // slowMo: 250, // slow things down by 250 ms
            ignoreDefaultArgs: [
                "--mute-audio",
            ],
            args: [
                "--autoplay-policy=no-user-gesture-required",
            ],
        });
        let [page] = await browser.pages(); // reuses/takes the default blank page
        // let page = await this.global.browser.newPage();

        page.on('console', async msg => console[msg._type](
            ...await Promise.all(msg.args().map(arg => arg.jsonValue()))
        ));
        this.global.page = page;
        this.global.browser = browser;
        this.global.jsdom = this.dom;
    }

    async teardown() {
        await this.global.browser.close();
        await super.teardown();
    }

    runScript(script) {
        return super.runScript(script);
    }
}

module.exports = ExpressEnvironment;
** tsconfig.json **
{
  "compilerOptions": {
    "target": "es2017"
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "src/**/*.test.ts"
  ]
}
** package.json **
{
  "scripts": {
    "test": "jest",
  },
  "jest": {
    "testEnvironment": "./testEnvironment.js",
    "globalSetup": "./globalSetup.js",
    "globalTeardown": "./globalTeardown.js",
    "transform": {
      "^.+\\.(ts|tsx)$": "ts-jest"
    }
  },
  "jshintConfig": {
    "esversion": 8
  },
  "dependencies": {
    "typescript": "^3.7.3"
  },
  "devDependencies": {
    "@types/express": "^4.17.6",
    "@types/jest": "^25.2.1",
    "@types/node": "^13.11.1",
    "@types/puppeteer": "^2.0.1",
    "express": "^4.17.1",
    "jest": "^25.3.0",
    "puppeteer": "^3.0.0",
    "ts-jest": "^25.3.1"
  }
}

Esta página foi útil?
0 / 5 - 0 avaliações

Questões relacionadas

potapovDim picture potapovDim  ·  4Comentários

jacekpl picture jacekpl  ·  4Comentários

eszthoff picture eszthoff  ·  3Comentários

tolmasky picture tolmasky  ·  4Comentários

machineghost picture machineghost  ·  4Comentários