我正在学习Mocha和Chai,我正在尝试编写一个测试来检查页面上H1标签的值。我在下面的测试中尝试以三种方式执行此操作:
quantity
我试图以https://github.com/nathanboktae/chai-dom#texttext所述的方式使用chai-dom扩展程序来执行此操作。 然而: 第一个测试通过但不应该通过(页面上的内容与测试声明的不同)
第二项测试报告错误const expect = require('chai').expect;
const assert = require('chai').assert;
const request = require('request');
const chaiHttp = require('chai-http');
const app = require('../../app');
const chai = require('chai');
chai.use(require('chai-dom'));
chai.use(chaiHttp);
//first attempt
describe('Story Homepage', function(){
it('Should have an H1 of My Home Page', function(){
chai.request(app)
.get('/', function (){
expect(document.querySelector('h1')).should.have.text('My Home Page');
});
})
});
//second attempt
describe('Story Page Tests', function () {
it('Homepage H1 is My Home Page', function(done) {
chai.request(app)
.get('/', function(done){
expect(document.querySelector('h1').should.have.text('My Home Page'));
done();
})
});
});
//third attempt
describe('Story Page Tests', function () {
it('Homepage H1 is My Home Page', function(done) {
chai.request(app)
.get('/')
.end(function(err, res) {
expect(document.querySelector('h1').should.have.text('My Home Page'));
done();
});
});
});
,但我认为我正在使用上方Error: Timeout of 15000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
。
第三个测试报告错误done
这似乎是合乎逻辑的,但我不确定如何解决它。
是否有人提供有关如何正确执行此操作的建议?
答案 0 :(得分:1)
你的第三次尝试是从异步mocha测试的角度正确编写的,但是你有一个根本的问题,就是你在Node.js中运行我的测试,你正在编写一个断言代码就好像它在浏览器。
如果您正在从节点发出HTTP请求并返回HTML响应,则图片中根本没有浏览器,这意味着没有DOM API而没有document
对象因此您的document is not defined error
。
如果您想在浏览器中进行单元测试。有许多方法可以做到这一点,但请尝试a simple tutorial like this开始。
答案 1 :(得分:0)
你好@Stuart我正在从事类似的工作,但我遇到了几乎相同的问题。通过到目前为止的尝试,我发现JS-DOM与chaidom结合使用非常有用。 因此,有一个简单的html构造函数来创建像这样的元素:
function HtmlElement(el) {
this.element = (el instanceof HTMLElement) ? el : document.createElement(el);
}
HtmlElement.create = function create(el) {
return new HtmlElement(el);
};
HtmlElement.prototype.addId = function addId(id) {
this.element.id = id || '';
return this;
};
...以及进一步的测试:
describe("Checks element methods presence on the prototype", function(){
it('should have addClass method', function () {
const ul = (new HtmlElement('ul').addId('some'));
console.log(ul.element);
ul.element.should.equal(`<ul id="some"></ul>`);
});
});
应该通过。
答案 2 :(得分:0)
我使用了node-html-parser
,建议您这样做:
https://www.npmjs.com/package/node-html-parser
这是我的代码:
import {parse} from 'node-html-parser';
import {expect} from 'chai';
import {describe, it, before} from 'mocha';
import request from 'supertest';
describe('Page Tests', async function () {
let page = null;
before(async function(){
const response = await request(server).get(workingTestUrl);
page = parse(response.text);
})
it('Should give a person page at test url', async function () {
const obituarySection = page.querySelector('#main-obituary');
expect(obituarySection).to.exist;
});
});