调用同一文件中的测试功能 [英] Testing function within same file is called

查看:101
本文介绍了调用同一文件中的测试功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个函数,其中一个函数调用另一个函数,另一个函数返回某些内容,但是我无法使测试正常进行.

I have 2 functions where one calls the other and the other returns something, but I cannot get the test to work.

使用expect(x).toHaveBeenCalledWith(someParams);期望使用间谍,但我不知道如何在同一文件中监视某个函数...

Using expect(x).toHaveBeenCalledWith(someParams); expects a spy to be used, but I am unaware of how to spy on a function within the same file...

错误::可能是间谍,但得到了功能.

Error: : Expected a spy, but got Function.

用法:Expect().toHaveBeenCalledWith(... arguments)

Usage: expect().toHaveBeenCalledWith(...arguments)

Example.ts

doSomething(word: string) {
   if (word === 'hello') {
      return this.somethingElse(1);
   }
   return;
}

somethingElse(num: number) {
   var x = { "num": num };
   return x;
}

Example.spec.ts

fake = {"num": "1"};

it('should call somethingElse', () => {
    component.doSomething('hello');
    expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
    expect(component.somethingElse(1)).toEqual(fake);
});

推荐答案

在您的Example.spec.ts中,只需添加spyOn(component, 'somethingElse');作为it('should call somethingElse ...测试的第一行:

In your Example.spec.ts, just add a spyOn(component, 'somethingElse'); as first line of your it('should call somethingElse ... test :

fake = {"num": "1"};

it('should call somethingElse', () => {
    // Add the line below.
    spyOn(component, 'somethingElse');
    component.doSomething('hello');
    expect(component.somethingElse).toHaveBeenCalledWith(1);
});

it('should return object', () => {
    expect(component.somethingElse(1)).toEqual(fake);
});

toHaveBeenCalledWith之前使用,Expect方法需要一个Spy作为参数(根据

The expect method needs a Spy as parameter when used before a toHaveBeenCalledWith (as per the Jasmine documentation).

这篇关于调用同一文件中的测试功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆