簡體   English   中英

Jest:測試功能時的邏輯問題

[英]Jest: Logic issue in testing a function

我想測試一個名為 getRunningContainers 的函數,它基本上返回我系統上所有正在運行的容器。 它在內部使用了兩個名為 listContainers 和 getContainer 的函數來工作。

  async getRunningContainers(): Promise<ContainerInspectInfo[] | undefined> {
    const runningContainers: ContainerInspectInfo[] = [];
    const opts: any = {
      filters: {
        status: ['running'],
      },
    };
    try {
      const containers: ContainerInfo[] = await this.client.listContainers(
        opts
      );

      for (const c of containers) {
        const container: ContainerInterface = await this.client.getContainer(
          c.Id
        );
        const containerInspect: ContainerInspectInfo = await container.inspect();
        runningContainers.push(containerInspect);
      }

      return runningContainers;
    } catch (err) {
      console.log(`running containers error: ${err}`);
      return;
    }
  }

我正在編寫以下 Jest 測試,其中 dummy_container 是一個表示容器的對象,dummy_container_response 是一個相同的數組,dummy_info 是一個表示 ContainerInspectInfo 的對象。 我從 getRunningContainer 返回undefined ,我似乎無法找出原因。

describe('Container Client', () => {
    let containerData = dummy_container_responses;
    const MockDockerClient = {
        listContainers: (opts: any) => new Promise((resolve, reject) => {
            resolve(dummy_info);
        }),

        createContainer: (opts:any) => new Promise((resolve, reject)=> {
            resolve(dummy_container);
        }),

        getContainer: (id: any) => new Promise((resolve, reject) => {
            resolve(dummy_container)
        })
    }

    const containerClient = new Container(MockDockerClient);

    test('starting a container', async() => {
        const container = await containerClient.create(dummy_container);
        const containers = await containerClient.getRunningContainers()

        expect(containers).toEqual(dummy_container)
       
        
    })
}) 

我不確定是否需要更多信息,所以請隨時告訴我是否需要。 謝謝!

import {
  Container as ContainerInterface,
  ContainerCreateOptions,
  ContainerInfo,
  ContainerInspectInfo,
  HostConfig,
} from 'dockerode';

export class Container {
  client: any;

  constructor(client: any) {
    this.client = client;
  }

  async create(
    opts: any
  ): Promise<ContainerInterface | undefined> {
    let container: ContainerInterface;
    const { name, Image, Cmd, HostConfig, Labels, Entrypoint, Env } = opts;
    try {
      const createOpts: ContainerCreateOptions = {
        name,
        Image,
        Cmd,
        HostConfig,
        Labels,
        Entrypoint,
        Env,
      };
      container = await this.client.createContainer(createOpts);
      return container;
    } catch (err) {
      console.log(`create container error: ${err}`);
      return;
    }
  }

  async getRunningContainers(): Promise<ContainerInspectInfo[] | undefined> {
    const runningContainers: ContainerInspectInfo[] = [];
    const opts: any = {
      filters: {
        status: ['running'],
      },
    };
    try {
      const containers: ContainerInfo[] = await this.client.listContainers(
        opts
      );

      for (const c of containers) {
        const container: ContainerInterface = await this.client.getContainer(
          c.Id
        );
        const containerInspect: ContainerInspectInfo = await container.inspect();
        runningContainers.push(containerInspect);
      }

      return runningContainers;
    } catch (err) {
      console.log(`running containers error: ${err}`);
      return;
    }
  }

  static newContainerConfig(
    oldContainer: ContainerInspectInfo,
    newImage: string
  ): ContainerCreateOptions {
    const config: ContainerCreateOptions = {
      name: oldContainer['Name'].replace('/', ''),
      Image: newImage,
      Cmd: oldContainer['Config']['Cmd'],
      HostConfig: oldContainer['HostConfig'],
      Labels: oldContainer['Config']['Labels'],
      Entrypoint: oldContainer['Config']['Entrypoint'],
      Env: oldContainer['Config']['Env'],
    };
    return config;
  }
}

由於您的dummy_container是 JSON - 您可能希望在MockDockerContainer實現您的getContainer方法, MockDockerContainer所示:


 const MockDockerClient = {
       //  ... current implementation ...

        getContainer: (id: any) => new Promise((resolve, reject) => {
            resolve({
              inspect: () => new Promise(res => res(dummy_container)),
            });
        })
    }

這是因為您正在等待 getContainer().inspect() 的結果 - 所以 inspect() 需要是一個基於異步/承諾的函數,它返回您期望的內容。 我假設這是您的容器的 JSON - 但這可能是錯誤的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM