typescript 如何在Jest中从上下文模拟库

lbsnaicq  于 2023-03-09  发布在  TypeScript
关注(0)|答案(1)|浏览(124)

我的.ts文件中有下一个代码:

import { getBuildUrl } from '../../service/navigationService';

const appUtils = require('../../utils/appUtils');

describe('Report Title suite tests', () => {

let getHostNameStub = jest.spyOn(appUtils, 'getHostName')
let getOrganizationNameStub = jest.spyOn(appUtils, 'getOrganizationName')
let getProjectNameStub = jest.spyOn(appUtils, 'getProjectName')

  describe('returnBuildUrl', () => {
    getHostNameStub.mockReturnValue("HostNametest")
    getOrganizationNameStub.mockReturnValue("OrganizationTest")
    getProjectNameStub.mockReturnValue("ProjectNameTest")
    
    it('should display title and description without report URL', async () => {
      expect(getBuildUrl("IdTest")).toBeDefined();
      expect(getBuildUrl("IdTest")).toEqual("https://HostNametest/OrganizationTest/ProjectNameTest/_build/results?buildId=IdTest")
    });
  });
});

正如您所看到的,appUtils方法是模拟的,但我在appUtils类中有下面的代码:const VSS_SDK = VSS;,例如:

const VSS_SDK = VSS;

    /**
     * return host name
     */
    export function getHostName() {
      return VSS_SDK.getWebContext().host.authority;
    }

VSS是在项目环境中提供的库
运行测试后,我收到错误:

Test suite failed to run

    ReferenceError: VSS is not defined

       8 |
       9 | // eslint-disable-next-line no-undef
    > 10 | const VSS_SDK = VSS;

是否可以模拟VSS库以避免此类错误?
getWebContext函数看起来像这样:

/**
        * Get the web context from the parent host
        */
function getWebContext(): WebContext;

和WebContext接口:

interface WebContext {
    account: HostContext;
    /**
    * Information about the Collection used in the current request (may be null)
    */
    collection: HostContext;
    /**
    * Information about the current request context's host
    */
    host: ExtendedHostContext;
    /**
    * Information about the project used in the current request (may be null)
    */
    project: ContextIdentifier;
    /**
    * Information about the team used in the current request (may be null)
    */
    team: TeamContext;
    /**
    * Information about the current user
    */
    user: UserContext;
}

使用建议的解决方案,我得到下一个错误:

Type '() => { host: { authority: string; }; }' is not assignable to type '() => WebContext'.
  Type '{ host: { authority: string; }; }' is missing the following properties from type 'WebContext': account, collection, project, team, userts(2322)
VSS.SDK.d.ts(201, 14): The expected type comes from property 'getWebContext' which is declared here on type 'typeof VSS
bjp0bcyl

bjp0bcyl1#

从我所看到的VSS是一个全局变量,它不为jest runner所知。
您需要为jest提供一种查看该变量的方法。
您有两个选项可以进行配置:

  • 设置文件
  • env之后的设置文件

您所需要做的就是编辑您的jest配置,并在其中添加一个选项,如下所示

{
  ...
  setupFiles: ['<rootDir>/setup.js'],
  ...
}

您可以在setup.js文件中声明任何全局变量,或者在执行测试之前做任何您想做的事情(这完全取决于您)。

global.VSS = {
  getWebContext: () => {
    return {
      host: {
        authority: 'My-authority'
      }
    };
  }
};

确保添加了测试运行中可能需要的所有属性和方法。

相关问题