【问题标题】:PACT.io: Getting Missing requests error and Error: Cross origin http://localhost forbiddenPACT.io:获取丢失的请求错误和错误:禁止跨源 http://localhost
【发布时间】:2021-08-24 20:07:24
【问题描述】:

我正在使用 Pact.io 在我的消费者中生成合同测试,但出现错误:

Missing requests: GET http://localhost:3001/productId/2857?date=2021-05-31

我将协议实例配置为在端口 3001 上运行,但我认为请求没有通过那里,因为我遇到了另一个错误:

Error: Cross origin http://localhost forbidden at dispatchError

我已经尝试过使用axios.defaults.adapter = require('axios/lib/adapters/http');

但我仍然在 dispatchError 处获得 Cross origin http://localhost 禁止。

已经尝试使用 jest --env=node"testEnvironment": "node" 但是这个选项破坏了我的代码:

ReferenceError: self is not defined

    > 1 | import { request } from './requests';

有人可以帮帮我吗?

我的代码是: package.json 代码:

...
"scripts": {
...
"test:consumer": "jest app/tests/contract/consumer/*.test.js --runInBand --setupFiles ./app/tests/helpers/pactSetup.js --setupTestFrameworkScriptFile=./app/tests/helpers/pactTestWrapper.js",

...
}
...

ContractTest_ClientsConsumer.test.js 代码:

import axios from 'axios';
import { Matchers } from '@pact-foundation/pact';
import { provider } from '../../helpers/pactSetup';
import viewApi from './viewApi';
import config from '../../../../app/config';

const getApiEndpoint = 'http://localhost:3001';
axios.defaults.adapter = require('axios/lib/adapters/http');

const productDateResponse = { value: 100, day: "2021-05-31" }

describe('Product Date', () => {
  afterEach(() => provider.verify());

  describe('Get Product Value', () => {
    beforeEach(() => {
      const interaction = {
        state: 'check some product value in some day',
        uponReceiving: 'value product in some day',
        withRequest: {
          method: 'GET',
          path: `${config.API_URL}/productId/2857?date=2021-05-31`,
          headers: {
            Accept: 'application/json, text/plain, */*',
          },
        },
        willRespondWith: {
          status: 200,
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
          },
          body: Matchers.somethingLike(productDateResponse),
        },
      };
      return provider.addInteraction(interaction);
    });

    test('returns correct body, header and statusCode', () => {
      console.log('Before calling getProduct');
      const response = viewApi.getProduct(2857, '2021-05-31', null);
      console.log('Called getProduct');
      console.log(response);
      console.log('After print response');
      expect(response.headers['content-type']).toBe('application/json; charset=utf-8');
      expect(response.data).toEqual(productDateResponse);
      expect(response.status).toEqual(200);
    });
  });
});

viewApi.js 代码:

import { request } from './requests';
import config from 'config';
import { response } from 'express';

export default class ViewApi {
  static getProduct(productId, date, requestDate = null) {
    try {
      const url = `${config.API_URL}/productId/${productId}`;
      let queryParams = `date=${date}`;

      if (requestDate) {
        queryParams += `&requestDate=${requestDate}`;
      }

      return request(`${url}?${queryParams}`);
  }
}

pactsSetup.js 代码:

import path from 'path';
import { Pact } from '@pact-foundation/pact';

export const provider = new Pact({
  port: 3001,
  log: path.resolve(process.cwd(), 'app/tests/contract/logs', 'mockserver-integration.log'),
  dir: path.resolve(process.cwd(), 'app/tests/contract/pacts'),
  spec: 2,
  logLevel: 'DEBUG',
  pactfileWriteMode: 'overwrite',
  consumer: 'pwa-store',
  provider: 'api-store',
});

pactTestWrapper.js 代码:

import { provider } from './pactSetup';

beforeAll(() => provider.setup());

afterAll(() => provider.finalize());

我定义了一个名为 API_URL 的环境变量: export API_URL=http://localhost:3001

【问题讨论】:

    标签: javascript testing axios jestjs pact


    【解决方案1】:

    我认为以下内容不会对您的 request 对象(我假设它是 axios 客户端?)产生影响,因为它发生在模块加载后,并且仅适用于默认客户端。

    axios.defaults.adapter = require('axios/lib/adapters/http');
    

    您也许可以直接将适配器应用到 request 客户端,但值得查看 Axios 文档。

    我认为这些是您的选择:

    1. 修复您的 ./request 客户端,以便使用更新的适配器对其进行配置
    2. 在 pact 对象上设置cors: true,这样它就会以OPTIONS 标头进行响应,就像通过网络应用程序发送它一样(似乎是默认模式)

    (2) 可能更有意义,因为它更符合您的实际使用情况。

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 2020-03-06
      • 2022-01-11
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2020-07-18
      • 1970-01-01
      相关资源
      最近更新 更多