javascript - mocha javascript单元测试返回html字符串的函数

标签 javascript unit-testing tdd mocha.js chai

我有一个从数组返回 html 字符串“”的函数,

尝试为其编写 Mocha 测试。但是如果我尝试断言相同,空格和\n 会给我带来困难,而且它也不能像测试字符串一样灵活地测试 html!。

如何为返回 html 字符串的纯函数编写测试?

示例:

renderHtml(json){
  // .. function that parse json and return <table> of its content.
}

如何测试这个功能?

  var mod = require('./render');
  var count = (s1,s2) => (s1.match(new RegExp(s2, 'gi'))||[]).length;
  describe('should handle simple array', function () {
    let json = [{ "id": "1", "name": "momen" }];
    let result = mod.renderHtml(json);

    it('should have 1 h1', function () {
      assert.equal(count(result, '<h1>'), 1);
    })

    it('should have 4 ths', function () {
      assert.equal(count(result, '<th>'), 4);
    })

    it('should have 2 tr', function () {
      assert.equal(count(result, '<tr>'), 2);
    })

    it('should have 2 td', function () {
      assert.equal(count(result, '<td>'), 2);
    })
  })

我想测试结果是否包含标签,以及包含 X 个 ths 和 X 个或每行包含 X 个 tds 的行的表格

最佳答案

怀疑您已经找到解决方案,但我最近遇到了类似的问题,但找不到答案。所以为了他人的利益。

问题完全相同,如何测试从 object/json 输入呈现 HTML block 的 typescript 类。我发现解决方案是使用cheerio插件(https://cheerio.js.org/)将html字符串转换为html对象,然后使用cheerio的jquery语法来访问元素和测试内容。我将通过提供解决方案中的工作示例来提供答案。

需要:npm install Cheerio --save-dev

我的渲染类:

constructor(private cardOverallStatus: ICardOverallStatus) {
}

@readOnly
public getTemplate() {
    return `
        <section class="goodservice">
            <h1>${this.cardOverallStatus.message}</h1>
        </section>
        ${this.getCardPartsTemplate()}
    `;
}

private getCardPartsTemplate(): string {
    if (!this.cardOverallStatus.modes || this.cardOverallStatus.modes.length === 0) {
        return "";
    }

    let template = `
        <section class="goodservice-list">
            <ul>
        `;
    this.cardOverallStatus.modes.forEach((mode) => {
        template += `<li>${mode}</li>`;
    });
    template += `
            </ul>
        </section>
        `;
    return template;
}

我的测试类(class):

import { CardOverallStatusTemplate } from './card-overall-status-template';
import { cardTypes } from "./../enums/card-types";
import { expect } from 'chai';
import * as cheerio from 'cheerio';
import 'mocha';

/* Just wanting to test the smallest part of the template - the card OverallStatus */
describe('Card Overall Status Template Unit-Test', () => {

  /* common constants */
  const bodyTag = 'body';
  const sectionTag = 'section';
  const h1Tag = 'h1';
  const liTag = 'li';
  const goodServiceClass = 'goodservice';
  const goodServiceListClass = 'goodservice-list';
  const goodServiceHeader = 'Good service on all lines';
  const tubeMode = 'Tube';
  const tramMode = 'Tram';

  describe('getTemplate() Unit-Test', () => {
    /* these variable must be defined exlcusively within this specific describe pattern, otherwise the final load is used for all tests */
    var template: CardOverallStatusTemplate;
    var result: string;
    var $: CheerioStatic;

    const cardOverallStatus = {
      'type': cardTypes.OVERALL_STATUS,
      'message': 'Good service on all lines',
      'modes': ['Tube', 'Overground', 'TfL Rail', 'DLR', 'Tram']
    };

    template = new CardOverallStatusTemplate(cardOverallStatus);
    result = template.getTemplate();
    $ = cheerio.load(result);

    it('should return two sections', () => {
      expect($(`${bodyTag} > ${sectionTag}`).length).to.equal(2);
    })
    it('should return first section with "goodservice" class', () => {
      expect($(`${bodyTag} > ${sectionTag}`).first().hasClass(goodServiceClass)).to.equal(true);
    })
    it('should return first section header with "Good service on all lines"', () => {
      expect($(`${bodyTag} > ${sectionTag}.${goodServiceClass} ${h1Tag}`).first().html()).to.equal(goodServiceHeader);
    })
    it('should return second section with "goodservice-list" class', () => {
      expect($(`${bodyTag} > ${sectionTag}`).first().next().hasClass(goodServiceListClass)).to.equal(true);
    })
    it(`should return second section with number of li items to match number of modes = ${cardOverallStatus.modes.length}`, () => {
      expect($(`${bodyTag} > ${sectionTag}.${goodServiceListClass} ${liTag}`).length).to.equal(cardOverallStatus.modes.length);
    })
    it('should return second section with first mode of "Tube"', () => {
      expect($(`${bodyTag} > ${sectionTag}.${goodServiceListClass} ${liTag}`).first().html()).to.equal(tubeMode);
    })
    it('should return second section with last mode of "Tram"', () => {
      expect($(`${bodyTag} > ${sectionTag}.${goodServiceListClass} ${liTag}`).last().html()).to.equal(tramMode);
    })
  })
})

关于javascript - mocha javascript单元测试返回html字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45041452/

相关文章:

javascript - 允许在滚动动画期间改变元素高度

javascript - 计算元素的后代

php - 单元测试中的依赖关系

java - 在java中测试如何检查接口(interface)的方法是否被调用?

unit-testing - TDD 中的重构细节

tdd - 后置条件和 TDD

javascript - 返回了 Google 距离矩阵 ZERO_RESULTS

javascript - 使用 CSS 将圆移动到边框顶部

unit-testing - C# - 单元测试 - 如何计算代码覆盖率

unit-testing - 为什么我们需要像 Easymock 、 JMock 或 Mockito 这样的模拟框架?