Javascript 在私有方法上使用 Jasmines spyon

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8475564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:08:38  来源:igfitidea点击:

using Jasmines spyon upon a private method

javascriptunit-testingjasmine

提问by user502014

is it possible to use Jasmine unit testing framework's spyon method upon a classes private methods?

是否可以在类私有方法上使用 Jasmine 单元测试框架的 spyon 方法?

The documentation gives this example but can this be flexivble for a private function?

文档给出了这个例子,但是对于私有函数来说这可以灵活吗?

describe("Person", function() {
    it("calls the sayHello() function", function() {
        var fakePerson = new Person();
        spyOn(fakePerson, "sayHello");
        fakePerson.helloSomeone("world");
        expect(fakePerson.sayHello).toHaveBeenCalled();
    });
});

回答by Luillyfe

Just add a generic parameter < any>to the spyon()function:

只需在spyon()函数中添加一个通用参数< any>

 spyOn<any>(fakePerson, 'sayHello');

It works on perfectly !

它完美地工作!

回答by jurl

if you use Typescript for your objects, the function isn't really private.
All you need is to save the value that returned from spyOncall and then query it's callsproperty.

如果您为对象使用 Typescript,则该功能并不是真正私有的。
您只需要保存从spyOn调用返回的值,然后查询它的calls属性。

At the end this code should work fine for you (at least it worked for me):

最后这段代码应该适合你(至少它对我有用):

describe("Person", function() {
    it("calls the sayHello() function", function() {
        var fakePerson = new Person();
        // save the return value:
        var spiedFunction = spyOn<any>(fakePerson, "sayHello");
        fakePerson.helloSomeone("world");
        // query the calls property:
        expect(spiedFunction.calls.any()).toBeFalsy();
    });
});

回答by A-Sharabiani

Let say sayHello(text: string)is a private method. You can use the following code:

假设sayHello(text: string)是一个私有方法。您可以使用以下代码:

// Create a spy on it using "any"
spyOn<any>(fakePerson, 'sayHello').and.callThrough();

// To access the private (or protected) method use [ ] operator:
expect(fakeperson['sayHello']).toHaveBeenCalledWith('your-params-to-sayhello');
  • Create a spy on private method using any.
  • To access the private (or protected) method use []operator.
  • 使用any.
  • 要访问私有(或受保护)方法,请使用[]运算符。

回答by omer

spyOn<any>(fakePerson, 'sayHello');
expect(fakePerson['sayHello']).toHaveBeenCalled();

by adding <any>to spyOn you remove it from typescript type check. you also need to use array index notation in order to access a private method (sayHello) in the test expect

通过添加<any>到 spyOn,您可以将其从打字稿类型检查中删除。您还需要使用数组索引符号来访问测试中的私有方法(sayHello)

回答by user3765649

In my case (Typescript):

就我而言(打字稿):

jest.spyOn<any, string>(authService, 'isTokenActual')

OR with mocked result:

或模拟结果:

jest.spyOn<any, string>(authService, 'isTokenActual').mockImplementation(() => {
  return false;
});

回答by Andreas K?berle

No cause you cant access a private function outside the context of your instance.

没有理由您无法访问实例上下文之外的私有函数。

Btw, its not a good idea to spy on objects you wanna test. When you test if a specific method in your class you want to test is called, it says nothing. Lets say you wrote the test and it passed, two weeks later you refactor some stuff in the function and add a bug. So your test is still green cause you the function called. B

顺便说一句,监视您要测试的对象不是一个好主意。当您测试您要测试的类中的特定方法是否被调用时,它什么也没说。假设你编写了测试并且它通过了,两周后你重构了函数中的一些东西并添加了一个错误。所以你的测试仍然是绿色的,因为你调用了函数。乙

Spies are useful when you work with Dependency Injection, where all external dependencies are passed by the constructor and not created in your class. So lets say you have a class that needs a dom element. Normaly you would use a jquery selector in the class to get this element. But how you wanna test that something is done with that element? Sure you can add it to your tests pages html. But you can also call your class passing the element in the constructor. Doing so, you can use spy to check if your class interacts with that element as you expected.

当您使用Dependency Injection 时,间谍很有用,其中所有外部依赖项都由构造函数传递,而不是在您的类中创建。因此,假设您有一个需要 dom 元素的类。通常,您会在类中使用 jquery 选择器来获取此元素。但是您想如何测试该元素是否完成了某些操作?当然你可以将它添加到你的测试页面 html 中。但是你也可以调用你的类,在构造函数中传递元素。这样做,您可以使用 spy 来检查您的类是否按预期与该元素进行交互。

回答by Koji D'infinte

Typescript gets compiled to javascript and in javascript every method is public. So you can use array index notation to access private methods or fileds, viz:

Typescript 被编译为 javascript,在 javascript 中,每个方法都是公开的。因此,您可以使用数组索引符号来访问私有方法或文件,即:

Object['private_field']

回答by StevenMcD

If you want to test private functions within a class, why not add a constructor to your class that signals that those private functions get returned?

如果你想测试一个类中的私有函数,为什么不向你的类添加一个构造函数来表示这些私有函数被返回呢?

Have a read through this to see what I mean: http://iainjmitchell.com/blog/?p=255

通读一遍以了解我的意思:http: //iainjmitchell.com/blog/?p=255

I have been using a similar idea and so far its working out great!

我一直在使用类似的想法,到目前为止效果很好!