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句言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' }

无论您使用expectassert,Chai在断言失败时会丢下错误。您应该不是处理错误,因为摩卡咖啡取决于错误以确定测试案例是否应该失败。

此外,如果您的测试案例异步,请记住返回诺言或在异步任务完成时致电done回调。

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

最新更新