3

我很想测试一些将 Promises 与chai-as-promisedand结合使用的代码Mocha。我的测试套件还利用fetch-mock来模拟通常使用 Fetch API 发送的 AJAX 请求。

这是我要测试的代码:

/**
 * Sends a POST request to save (either insert or update) the record
 * @param  {object} record simple object of column name to column value mappings
 * @return {Promise}       Resolves when the POST request full response has arrived.
 * Rejects if the POST request's response contains an Authorization error.
 */
save(record) {
  var _this = this;
  return this._auth(record)
    .then(function() {
      return window.fetch(_this._getPostUrl(), {
        method: 'post',
        headers: {
          'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: _this._objToPostStr(record),
        credentials: 'include'
      });
    })
    .then(function(saveResp) {
      return saveResp.text();
    })
    .then(function(saveResp) {
      return new Promise(function(resolve, reject) {
        if (saveResp.indexOf('Authorization') !== -1) {
          reject('Request failed');
        } else {
          resolve(saveResp);
        }
      });
    });
}

在我的最上层中describe,我有这个最初设置我的fetchMock对象的函数。

before(() => {
  fetchMock = new FetchMock({
    theGlobal: window,
    Response: window.Response,
    Headers: window.Headers,
    Blob: window.Blob,
    debug: console.log
  });
  fetchMock.registerRoute({
    name: 'auth',
    matcher: /tlist_child_auth.html/,
    response: {
      body: 'authResp',
      opts: {
        status: 200
      }
    }
  });
});

这是相关的测试代码:

describe('save', () => {
  it('save promise should reject if response contains the string Authorization', () => {

    fetchMock.mock({
      routes: ['auth', {
        name: 'save',
        matcher: /changesrecorded.white.html/,
        response: {
          body: 'Authorization',
          opts: {
            status: 200
          }
        }
      }]
    });

    let _getLocationStub = sinon.stub(client, '_getLocation');
    _getLocationStub.returns('/admin/home.html');

    client.foreignKey = 12345;
    let promise = client.save({
      foo: 'bar'
    });
    promise.should.eventually.be.fulfilled;
    fetchMock.unregisterRoute('save');
  });
});

我在调用中定义save路由的原因fetchMock.mock()是我有另一个测试需要save重新定义路由以返回其他内容。

为了确保 chai-as-promised 确实有效并且会通知我测试失败,我写了一个失败的测试promise.should.eventually.be.fulfilled;save这将失败,因为如果响应包含,则返回的 Promise将拒绝Authorization,它确实如此。Chrome 控制台显示 AssertionError message: expected promise to be fulfilled but it was rejected with 'Request failed,但我的 Mochatest-runner.html页面显示此测试通过。出于某种原因,chai-as-promised 无法与 Mocha 正确通信。

如果你想看我的整个项目,请在 Github 上查看这个 repo 。

任何想法为什么?

编辑:

这是我的测试设置代码:

let expect = chai.expect;
mocha.setup('bdd');
chai.should();
chai.use(chaiAsPromised);
4

1 回答 1

5

该值promise.should.eventually.be.fulfilled是一个承诺,您应该返回它,以便 Mocha 可以知道您的测试何时结束。我创建了一个小测试文件来模拟您所看到的内容,如果像您一样,我只是无法返回,我可以完全复制该行为promise.should.eventually.be.fulfilled;。这是一个有效的示例:

import chai from "chai";
import chaiAsPromised from "chai-as-promised";

chai.use(chaiAsPromised);
chai.should();

describe("foo", () => {
    it("bar", () => {
        let promise = Promise.reject(new Error());
        return promise.should.eventually.be.fulfilled;
    });
});

在您的代码中,您在测试结束时有一些清理代码:fetchMock.unregisterRoute('save');. 根据您显示的内容,我会将其移至after钩子上,以使其反映您的before钩子。通常,after应执行与 inbeforeafterEachin相对应的清理beforeEach。但是,如果您出于某种原因需要在测试中包含清理代码,您可以这样做:

        function cleanup() {
            console.log("cleanup");
        }

        return promise.should.eventually.be.fulfilled.then(
            // Called if there is no error, ie. if the promise was
            // fullfilled.
            cleanup,
            // Called if there is an error, ie. if the promise was
            // rejected.
            (err) => { cleanup(); if (err) throw err; });

不幸的是,Chai 似乎返回了一些看起来像 ES6Promise但只是部分的东西。最终,它可能会返回一个实际的 ES6 承诺,然后.finally无论发生什么,您都可以调用以运行清理代码,并让错误自动传播。

于 2015-10-12T16:52:22.660 回答