代码之家  ›  专栏  ›  技术社区  ›  Leon Gaban

PACT.io:运行npm run pactTest时,获取缺少的请求错误

  •  0
  • Leon Gaban  · 技术社区  · 6 年前

    已创建测试回购: https://github.com/leongaban/pact-io-js-test

    enter image description here

    预期

    npm run pactTest 它将为我的 TotalPayout.test.pact.ts 文件。

    D, [#38238] DEBUG -- : {
      "description": "a GET request with a user id",
      "request": {
        "method": "GET",
        "path": "/frontoffice/api/liquidity-pool/get-total-payout",
        "headers": {
          "Accept": "application/json"
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json"
        }
      }
    }
    W, [#38238]  WARN -- : Verifying - actual interactions do not match expected interactions. 
    Missing requests:
      GET /frontoffice/api/liquidity-pool/get-total-payout
    
    
    W, [#38238]  WARN -- : Missing requests:
      GET /frontoffice/api/liquidity-pool/get-total-payout
    

    这是我的契约文件

    // @ts-ignore
    import path from 'path';
    // @ts-ignore
    import { Pact } from '@pact-foundation/pact';
    import { getTotalPayout } from './LiquidityPool';
    
    // const port = 12345;
    const endpoint = '/frontoffice/api/liquidity-pool/get-total-payout';
    
    const EXPECTED_BODY = {
      total_payout: 100.21,
    };
    
    const userId = 'foo';
    
    describe('The API', () => {
      // Copy this block once per interaction under test
      describe('getUsersTotalPayout', () => {
        beforeEach(() => {
          const interaction = {
            uponReceiving: 'a GET request with a user id',
            withRequest: {
              method: 'GET',
              path: endpoint,
              headers: {
                Accept: 'application/json',
              },
            },
            willRespondWith: {
              status: 200,
              headers: {
                'Content-Type': 'application/json'
              },
              data: EXPECTED_BODY
            },
          };
    
          // @ts-ignore
          return provider.addInteraction(interaction);
        });
    ​
        // add expectations
        it('Should call getUsersTotalPayout and return an object with the total_payout', done => {
          getTotalPayout(userId)
            .then((response: any) => {
              console.log('response', response);
              console.log('EXPECTED_BODY', EXPECTED_BODY);
              expect(response).toEqual(EXPECTED_BODY);
            })
            .then(done);
        });
      });
    });
    

    下面是包含 getTotalPayout

    这个端点还不存在,但我的理解是,这个Pact测试应该仍然有效。

    // @TODO Note, this is the placeholder for LiquidityPool API endpoints
    // @ts-ignore
    import axios, * as others from 'axios';
    
    const endpoint = '/frontoffice/api/liquidity-pool/';
    
    export const getTotalPayout = async (userId: string) => {
      const response = await axios.get(`${endpoint}get-total-payout`, { params: userId });
      return response.data;
    };
    

    也是我的 axios 模仿 src/__mocks__/axios.ts

    // tslint:disable-next-line:no-empty
    const mockNoop = () => new Promise(() => {});
    
    export default {
      get: jest.fn(() => Promise.resolve({ data: { total_payout: 100.21 }})),
      default: mockNoop,
      post: mockNoop,
      put: mockNoop,
      delete: mockNoop,
      patch: mockNoop
    };
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   Matthew Fellows    6 年前

    很简单-你的测试是 击中路径 /frontoffice/api/liquidity-pool/get-total-payout

    你要去跑步了 http://localhost:1234

    在axios配置中,您模拟了http请求库,因此它什么也不做。因此,当您的实际代码使用它时,它不会使http调用和Pact测试失败,因为它期望一个具有特定形状的调用,但没有得到它。

    以下是您需要更改的内容:

    1. 模拟Axios是为了提供固定的响应,在Pact测试期间不要模拟Axios(如果您愿意,本地开发人员可以这样做),因为这将阻止对Pact进行真正的调用。Pact需要对它进行真正的http调用,这样它就可以检查你的代码是否做了正确的事情,然后将它发现的内容写入一个“契约”

    pactSetup.ts包:

      // Configure axios to use the Pact mock server for Pact tests
      import axios from "axios";
      axios.defaults.baseURL = "http://localhost:1234";
    
    1. 读取Pact吐出的日志文件。它告诉你发生了什么。重复:您已经告诉Pact,在上应该有一个交互 但它从未收到过。让你真正的代码打这个,然后你就没事了。

    最后,顺便说一句,一旦开始生成Pact(在1-4修复之后),您可能希望将Pact用作本地开发的本地存根服务器。这个二进制文件实际上已经安装在你的node\u模块中了,关于它如何运行的文档也在这里 https://github.com/pact-foundation/pact-ruby-standalone/releases

      "stubs": "$(find . -name pact-stub-service | head -n 1) pacts/* --port 4000"
    

    然后你就可以跑了 npm run stubs 并在端口4000上运行提供程序的本地存根,其中包含您在测试中输入的所有请求/响应。