简体   繁体   English

将 Jest 用于打字稿中的方法

[英]Use Jest for a method in typescript

I'm using for the first time jest.我是第一次使用 jest。 So I want to test this method:所以我想测试这个方法:

public static getProjectBranch(toto: any): string {
    if ("branch" in toto) {
        return toto.branch;
    } else {
        return "master";
    }
}

This method is inside a class totoService.ts此方法在类 totoService.ts 中

What I'm doing in totoService.spec.ts :我在 totoService.spec.ts 中所做的:

describe("Test get Project Branch", () => {
test("branch is in component", () => expect(getProjectBranch()).toBe(""));
});

I want to know if what i'm doing is good or no And how can I import the method getProjectBranch in the file ?我想知道我在做什么是好还是不好 我怎样才能在文件中导入 getProjectBranch 方法?

As your method getProjectBranch is static you could simply do like shown below:由于您的方法getProjectBranch是静态的,您可以简单地执行如下所示:

describe("TotoService",() => {
  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''}; //create your test object here
      expect(totoService.getProjectBranch(toto)).toEqual(''); //call static method of TotoService
    })
  })
})

If you would like to call non static methods you need to create an instance of the totoService beforeEach test:如果你想调用非静态方法,你需要在beforeEach测试之前创建一个 totoService 的实例:

describe("TotoService",() => {

  let totoService;

  beforeEach(() => {
    totoService = new TotoService();
  })

  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''};
      expect(totoService.getProjectBranch(toto)).toEqual('');
    })
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM