使用JEST测试DOM元素

时间:2019-02-20 04:47:46

标签: javascript node.js jestjs

我正在尝试使自己熟悉JEST,因此我意识到自己可能在这方面是错误的。。。但是我想编写一个验证我的索引页面标题的测试,因此我参考了此文档:{{3} }。

这是测试:

128x128

这就是我的index.html的样子。

import 'whatwg-fetch'
test('H1 in index says Users', () =>{
  //Set up our document body - this is probably my problem...
  document = fetch("/index.html").then(onSuccess, onError);
  //This succeeds:
  //document.body.innerHTML ="<h1>Users</h1>"
  function onSuccess(response) {
    return response.text();
  }
  function onError(error){
    console.log(error);
  }
  const $ = require('jquery');
  expect($("h1").text()).toEqual("Users");
});
当我尝试获取index.html时,

expect()为空。

2 个答案:

答案 0 :(得分:1)

不熟悉Jest,但是由于获取是异步的,因此无法在then子句之外获取获取结果。考虑将expect放在onSuccess内。请查看https://jestjs.io/docs/en/asynchronous.html,了解处理异步测试的示例。

此外,获取html不会返回该html文件的DOM对象,而是返回原始文本内容,因此jQuery无法使用。您需要通过例如DOMParser将原始文本解析为DOM,然后对DOM进行测试。

最后,您需要导入的所有内容都应放在文件顶部,因此将var $ = require('jquery')移到测试功能之外

示例代码(测试)

import 'whatwg-fetch'
import $ from "jquery"

test('H1 in index says Users', () =>{
  function onSuccess(response) {
    const rawHTML = response.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(rawHTML, 'text/html');

    const h1Text = $(doc).find('h1').text();
    expect(h1Text).toEqual('Users');
    done();
  }

  function onError(error){
    console.log(error);
  }

  fetch("/index.html").then(onSuccess, onError);
});

答案 1 :(得分:0)

以下使用提取来解决我的问题-但我不相信这是复习有关模拟提取的JEST文档的最佳答案:

//replaced 'whatwg-fetch' - was getting Network Request Failed errors
import fetch from 'isomorphic-fetch';
//moved to top of the document
import $ from "jquery";

//added (done) parameter as per JEST documentation for async calls
test('H1 in index says Users', (done) => {
  function onSuccess(response){
    return response.text();
  }
  function onError(error){
    //updated to throw error as per JEST documentation
    throw new Error(error);
  }
  //fetch requires an absolute URL - therefore server needs to be running,
  //this is fine when jest is being watched, however would require a
  //config file to run tests in multiple environments, 
  //may be a better alternative
  const baseUrl = 'http://localhost:1337';
  fetch(baseUrl+'/').then(onSuccess, onError).then(function(response) {
    //using this format since it was in JEST documentation for DOM manipulation
    document.body.innerHTML = response;

    expect($('h1').text()).toEqual('Users');
    done();
  });
});