Big*_*ney 6 testing node.js express supertest
所以现在的输出是:
Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises
Warning: .end() was called twice. This is not supported in superagent
GET /api/things 200 3.009 ms - 2414
superagent: double callback bug
WARNING
问题是,我需要res从调用中返回的对象.end()来测试 ETag 功能。它永远不会进入第二个.end(),也不会打印出该控制台日志。
最里面的.catch(done)是被调用的那个。
it('should return things', done => {
  const promises = [];
  promises.push(Thing.create(testThing));
  promises.push(Thing.create(testThing));
  Promise.all(promises)
    .then(things => {
      request(app)
        .get('/api/things')
        .expect(200)
        .end((err, res) => {
          const etag = res.get('ETag')
          if (err)
            return done(err);
          request(app)
            .get('/api/things')
            .set('If-None-Match', etag)
            .expect(304)
            .end((err, res) => {
              console.log('are we able to make it back here?');
              expect(err).to.not.exist;
              expect(res.body.data).to.be.undefined;
              expect(res.get('ETag')).to.be.equal(etag);
              return done(err);
            })
        })
        .catch(done);
    })
    .catch(done);
});
});
有谁知道为什么会发生这种情况,以及如何测试这样的事情?
为此浪费了1个小时。
官方文档不太好: https: 
//www.npmjs.com/package/supertest
以下工作正常:
let request = require("supertest");
var assert = require("assert");
// const chai = require("chai");                     // can be chai instead of assert
describe("Run tests", () => {
  request = request("http://localhost:3001");        // must be here
  it("get", async () => {
    request
      .get("/")
      .expect("Content-Type", /json/)
      .expect(200)
      .then((response) => {                          // must be then, not a callback
        assert(response.body.data !== undefined);
      })
      .catch((err) => {
        assert(err === undefined);
      });
  });
});
我想通了,我正在做以下事情:
if (req.header('If-None-Match') === allThingsEtag) {
    // dont send allThings
    res.status(304);
}
我需要实际设置响应的正文,以便它知道返回它,如下所示:
if (req.header('If-None-Match') === allThingsEtag) {
    // dont send allThings
    res.status(304);
    res.json();
}
我知道这对于我的情况来说非常特殊,但万一有人也遇到这个问题,这就是我必须想出的解决方案。所以也许检查你的 api 代码。
为了解决.end()被调用两次的问题,我将测试更改为使用.then().
| 归档时间: | 
 | 
| 查看次数: | 11816 次 | 
| 最近记录: |