【问题标题】:mocha javascript unit testing a function that return html stringmocha javascript单元测试返回html字符串的函数
【发布时间】:2017-07-11 17:51:11
【问题描述】:

我有一个函数可以从数组中返回一个 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 个 ths 和 X 个数的表或每行包含 X 个 tds 的行

【问题讨论】:

    标签: javascript unit-testing tdd mocha.js chai


    【解决方案1】:

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

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

    要求:npm installcheerio --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);
        })
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2015-01-06
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多