使用IS是DOM Elements测试

问题描述 投票:0回答:2

我正在尝试熟悉JEST,所以我意识到我可能在这里越位...但我想编写一个测试来验证我的索引页面的标题,我引用了这个文档:https://jestjs.io/docs/en/tutorial-jquery

这是测试:

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的样子。

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
    <h1>Users</h1>
  </body>
</html>

当我尝试获取index.html时,expect()为空。

javascript node.js jestjs
2个回答
1
投票

不熟悉Jest,但由于fetch是异步的,因此无法在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);
});

0
投票

下面是使用fetch解决我的问题 - 但我不相信这是最好的答案将审查有关模拟获取的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();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.