如何测试引用html文件中html元素的JavaScript代码

时间:2018-11-10 04:28:53

标签: javascript unit-testing mocha chai jsdom

我是JavaScript及其测试库的新手。我一直在尝试使用mocha,chai和JSDOM进行单元测试。我尝试了不同的资源来学习,但是没有一个以对于初学者来说容易理解的方式进行了解释。我想出了一个简单的测试。我知道我在测试中做错了很多事情,希望有人可以帮助您进行测试,甚至可以提供满足我需要的不错的资源。

我的测试

const {JSDOM} = require('jsdom');
const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');

global.window = dom.window;
global.document = dom.window.document;


const Auths = require('../UI/js/login.js')
auth = Auths("sammy@gmail.com","sa!@##$")


var assert = require('chai').assert;
describe('Login', function() {
  it('should return a wrong email or password for invalid login', function() {

    assert.equal(document.getElementById("erroMessage").value,"wrong email or password")

  });
});

正在尝试测试的代码

class Auths {

  constructor(email,password) {
    this.email = email
    this.password = password

  }


  // this function is called when the litsener responds to submit eve
  login(){


    // url for endpoint
    let url = "http://127.0.0.1:5000/api/v2/users/login"

    // get login data from ui
    let data = {
      email : this.email,
      password : this.password
    };



    // define data to be used in options section
    let fetchData = {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body:JSON.stringify(data)

    };

    // use the fetch api
    fetch(url,fetchData)
    .then(function(response){return response.json()})
    .then(function(response){

      // store data fore use after login
      localStorage.setItem('token',response.token);
      localStorage.setItem('role',response.role);
      localStorage.setItem('names',response.names);

      // login the user
      if(response.message === "wellcome "+response.names +", "+"you are loged in as "+response.role){

        // login admin
        if(response.role == "admin"){
          window.location.href = 'UI/Admin/admin.html';
        }

        // login store attendant
        else{
          window.location.href = 'UI/Attendant.html';
        }
      }

      // respond to wrong cridentials
      else {
        document.getElementById("erroMessage").innerHTML = response.message;
      }

    })
  }

}

let login = document.getElementById('login');
login.addEventListener('submit', function getTarget(e){
  e.preventDefault()
  let email = document.getElementById('email').value;
  let password = document.getElementById('password').value;
  auth = new Auths(email, password);
  auth.login();
})

module.exports = Auths;

我遇到的错误

  

TypeError:无法读取null的属性'addEventListener'       在对象。 (A:\ sammy \ New文件夹\ ADC1-ADC4_Store_Manager \ UI \ js \ login.js:70:7)

1 个答案:

答案 0 :(得分:0)

页面上的元素未定义。您可以将它们写入测试中的文档。请参阅下面的更改代码。但是,您确实要调用auth.login(),这会导致login.js内的提取错误。因此,我考虑考虑一个可以模拟调用和响应的模拟框架,以便可以验证响应逻辑是否有效。

const { JSDOM } = require('jsdom');
const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');
const assert = require('assert');

global.window = dom.window;
global.document = dom.window.document;
global.document.write('<button type="button" id="login"> Login</button >')
global.document.write('<input id="erroMessage" value="wrong email or password">')

const Auths = require('../js/login.js')
auth = new Auths("sammy@gmail.com", "sa!@##$")

describe('Login', function () {
    it('should return a wrong email or password for invalid login', function () {
        assert.equal(document.getElementById("erroMessage").value, "wrong email or 
          password")
    });
});