在测试承诺时如何确保断言实际上是通过还是失败?

时间:2017-06-22 07:04:45

标签: javascript unit-testing mocha sinon chai

这是我的这个问题的后续问题:How to test an ES6 class that needs jquery?

我最终将我的测试跑者改为karma&到目前为止它一直很好。唯一的问题是我不认为我的断言是有效的。

这是我使用mocha撰写的第一个单元测试,sinon& chai

import {Weather} from '../js/weather';
import chai from 'chai';
import sinon from 'sinon';

let assert = chai.assert;

describe('weatherbot', function() {
    beforeEach(() => {
        this.xhr = sinon.useFakeXMLHttpRequest();

        this.requests = [];
        this.xhr.onCreate = function(xhr) {
            this.requests.push(xhr);
        }.bind(this);
    });

    afterEach(() => {
        this.xhr.restore();
    });

    it('should return a resolved promise if call is successful', () => {
        let weather = new Weather(43.65967339999999, -79.72506369999999);

        let data = '{"coord":{"lon":-79.73,"lat":43.66},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":15.28,"pressure":1009,"humidity":82,"temp_min":13,"temp_max":17},"visibility":24140,"wind":{"speed":7.2,"deg":30},"clouds":{"all":90},"dt":1496770020,"sys":{"type":1,"id":3722,"message":0.0047,"country":"CA","sunrise":1496741873,"sunset":1496797083},"id":5907364,"name":"Brampton","cod":200}';

        weather.getWeather().then((data) => {
            //assert.strictEqual(data.main.temp, 15.2);
            assert.strictEqual(true, false, 'these booleans are strictly equal');
        });

        this.requests[0].respond(
            200,
            { "Content-Type": "application/json" },
            data
        );
    });
});

如果你看第二个断言,它实际上应该失败,但令人惊讶的是它通过了。

这是我正在测试的课程,请注意我已经修复了jquery导入:

import * as jQuery from 'jquery'

export class Weather {
    /**
     * Constructor for Weather class
     *
     * @param latitude
     * @param longitude
     */
    constructor(latitude, longitude) {
        this.latitude  = latitude;
        this.longitude = longitude;
    }

    /**
     * Fetches the weather using API
     */
    getWeather() {
        return $.ajax({
            url: 'http://localhost:8080/weather?lat=' + this.latitude + '&lon=' + this.longitude,
            method: "GET",
        }).promise();
    }
}

此处还有我的karma配置:

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],


    // list of files / patterns to load in the browser
    files: [
        'test/*.js',
        'node_modules/jquery/dist/jquery.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'test/*.js': ['webpack','babel']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

最后测试的输出,可能有点长:

→ karma start
Hash: e0bdc8cc97632b01d813
Version: webpack 2.6.1
Time: 53ms
webpack: Compiled successfully.
webpack: Compiling...
22 06 2017 12:29:04.006:WARN [karma]: No captured browser, open http://localhost:9876/
Hash: a6bb01d664bd0198774e
Version: webpack 2.6.1
Time: 1604ms
        Asset     Size  Chunks                    Chunk Names
test/index.js  1.46 MB       0  [emitted]  [big]  test/index.js
chunk    {0} test/index.js (test/index.js) 1.45 MB [entry] [rendered]
    [5] ./~/sinon/lib/sinon/util/core/deep-equal.js 2.69 kB {0} [built]
   [14] ./~/sinon/lib/sinon/call.js 6.51 kB {0} [built]
   [20] ./~/sinon/lib/sinon/assert.js 6.94 kB {0} [built]
   [21] ./~/sinon/lib/sinon/util/core/deprecated.js 999 bytes {0} [built]
   [25] ./~/sinon/lib/sinon/util/fake_server.js 7.97 kB {0} [built]
   [26] ./~/sinon/lib/sinon/util/fake_timers.js 799 bytes {0} [built]
   [27] ./~/sinon/lib/sinon/util/fake_xml_http_request.js 20.2 kB {0} [built]
   [42] ./~/sinon/lib/sinon/collection.js 2.97 kB {0} [built]
   [43] ./~/sinon/lib/sinon/mock-expectation.js 7.77 kB {0} [built]
   [54] ./js/weather.js 531 bytes {0} [built]
   [55] ./~/chai/index.js 40 bytes {0} [built]
   [56] ./~/sinon/lib/sinon.js 2.6 kB {0} [built]
  [106] ./~/sinon/lib/sinon/sandbox.js 3.8 kB {0} [built]
  [112] ./~/sinon/lib/sinon/util/core/index.js 820 bytes {0} [built]
  [119] ./test/index.js 1.38 kB {0} [built]
     + 105 hidden modules
webpack: Compiled successfully.
22 06 2017 12:29:04.029:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:9876/
22 06 2017 12:29:04.029:INFO [launcher]: Launching browser Chrome with unlimited concurrency
22 06 2017 12:29:04.085:INFO [launcher]: Starting browser Chrome
22 06 2017 12:29:05.872:INFO [Chrome 59.0.3071 (Mac OS X 10.12.5)]: Connected on socket _FwfzgJZO3uGGE3xAAAA with id 76410708

  weatherbot
    ✓ should return a resolved promise if call is successful

Chrome 59.0.3071 (Mac OS X 10.12.5): Executed 1 of 1 SUCCESS (0.02 secs / 0.009 secs)
TOTAL: 1 SUCCESS

我在这里搜索过很多&我似乎正在按照我的方式测试这个承诺,但我想我在这里错过了一些东西。我怀疑sinon可能是这里的罪魁祸首。它也应该归还承诺。

1 个答案:

答案 0 :(得分:1)

是的,你缺少something:承诺必须由测试函数返回,或者你需要调用完成的回调

return weather.getWeather().then((data) => {
            //assert.strictEqual(data.main.temp, 15.2);
            assert.strictEqual(true, false, 'these booleans are strictly equal');
    });