繁体   English   中英

摩卡javascript单元测试返回html字符串的函数

[英]mocha javascript unit testing a function that return html string

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

尝试为此编写摩卡测试。 但是如果我尝试断言相同,则空格和\\ 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数和X数的表,或包含X数TDS的行,每行

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

问题是完全一样的,如何测试从对象/ json输入呈现HTML块的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;
}

我的测试课:

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);
    })
  })
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM