javascript - 在测试 Promise 时如何确保断言实际上通过或失败?

标签 javascript unit-testing mocha.js 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

我在这里用谷歌搜索了很多,看来我正在按照我应该的方式测试这个 promise ,但我认为我在这里遗漏了一些东西。我怀疑sinon可能是这里的罪魁祸首,它也应该返回 promise 。

最佳答案

是的,你失踪了something :promise必须由测试函数返回,否则需要调用done回调

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

关于javascript - 在测试 Promise 时如何确保断言实际上通过或失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44692382/

相关文章:

java - 检查 EasyMock 上是否调用了方法

javascript - 如何在调用时从 spy.on(object, 'funcName') 返回虚假数据?

javascript - 尝试通过 mocha 调试程序(使用 --debug-brk)调试 mocha 本身

javascript - 如何从 JavaScript 调用 ASHX?

javascript - 检查和设置表格行的可见性

jquery - BackboneJS 中的路由器实例不同

java - 在不继承抽象类的情况下模拟对抽象类的公共(public)方法的调用,最好使用 mockito

javascript - 使用 Mocha、Chai、chaiAsPromised 和 Sinon 测试 js promises

javascript - d3 路径仅显示路径/线最多 328 个点而不是 329 个或更多

javascript - slim 框架和 ajax。 '/' 字符作为参数