我用来在/环境nock
中拦截我的 http 请求。我也在使用并查询我自己的服务器。像这样:mocha
chai
supertest
supertest-chai
express
从“摩卡”进口{它};进口柴,{应该}从“柴”;
import request from 'supertest';
import supertestChai from 'supertest-chai';
import Joi from 'joi';
import chaiJoi from 'chai-joi';
// others
function itRespondsTo({ url, response, description, parameters = {} }) {
const maxAge = parameters.maxAge || serverConfig.defaultCacheAge;
const params = parameters ? `${Object.entries(parameters).map(([name, val]) => `&${name}=${val}`).join('&')}` : '';
const path = `/oembed?url=${encodeURIComponent(url)}${params}`;
const desc = description || `/oembed?url=${url}${params}`;
it(`should respond to ${desc}`, (done) => {
request(server)
.get(path)
.expect(200)
.expect('Content-Type', /json/)
.expect('Access-Control-Allow-Methods', 'GET')
.expect('Cache-Control', `public, max-age=${maxAge}`)
.expect(res => Object.values(OEMBED_TYPES).should.include(res.body.type)) // [1]
.expect(res => Joi.validate(res.body, OEMBED_SCHEMAS[res.body.type]).should.validate)
.expect(response)
.end(done);
});
}
describe('YouTube endpoint', () => {
beforeEach(() => {
nock(/youtube\.com/)
.reply(200, remoteResponse);
});
afterEach(() => {
nock.restore();
});
itRespondsTo({ url: 'https://youtu.be/m4hklkGvTGQ', response });
itRespondsTo({ url: 'https://www.youtube.com/embed/m4hklkGvTGQ', response });
itRespondsTo({ url: 'https://www.youtube.com/watch?v=m4hklkGvTGQ', response });
itRespondsTo({ url: 'https://www.youtube.com/?v=m4hklkGvTGQ', response });
});
当我运行我的测试时,第一次调用itRespondsTo
总是会抛出一个错误:
1)YouTube端点“在每个”钩子之前“应该响应/oembed?url= https://youtu.be/m4hklkGvTGQ ”:
TypeError:nock.reply 不是函数
而且它永远是第一个调用itRespondsTo
。如果我删除第一个调用,下一个调用将引发错误,依此类推。我不知道为什么会这样。