首页 > 解决方案 > chai 如何使用期望显示测试失败?

问题描述

chai 中的断言失败不会将测试报告为失败。

我尝试过使用断言而不是期望。我尝试通过缺少预期值中的字符来导致测试失败。

const axios = require('axios');
var assert = require('assert');
var expect = require('chai').expect;

describe('Tests', function() {
    describe('#indexOf()', function() {
        it('should return -1 when the value is not present', function() {
            assert.equal([1, 2, 3].indexOf(4), -1);
        });
        it('should return 1 when index is 2', function () {
           assert.equal([1, 2, 3].indexOf(3), 2)
        });
    });

    describe('#http-get', function () {
        it('should be https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg', function () {
           axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
                .then(response => {
                    // assert.equal(response.data.url, 'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg');
                    expect(response.data.url).to.equal('https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jp');
                })
                .catch(error => {
                    console.log(error);
                });
        });
    });
});

我预计输出状态为 2 通过和 1 失败,但我看到以下输出,其中第三个断言标记为通过,但打印了断言失败。

  Tests
    #indexOf()
      ✓ should return -1 when the value is not present
      ✓ should return 1 when index is 2
    #http-get
      ✓ should be https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg


  3 passing (34ms)

{ AssertionError: expected 'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg' to equal 'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jp'
    at axios.get.then.response (/Users/adityai/nodejs-workspace/axios-sample/test/axios-sample-test.js:20:50)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
  message: 'expected \'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg\' to equal \'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jp\'',
  showDiff: true,
  actual: 'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg',
  expected: 'https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jp' }

标签: node.jsweb-servicesmocha.jschaiassert

解决方案


无论您使用expector assert,当断言失败时,chai 都会抛出错误。您不应该处理该错误,因为 Mocha 依赖于错误来确定测试用例是否应该失败。

此外,如果您的测试用例是异步的,请记住done在异步任务完成时返回 Promise 或调用回调。

describe('#http-get', function () {
  it('should be https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jpg', function () {
    return axios.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
      .then(response => {
        expect(response.data.url).to.equal('https://apod.nasa.gov/apod/image/1905/volcano_stefnisson_960.jp')
      })
      // .catch(error => {
      //   console.log(error);
      // })
    })
})

推荐阅读