错误:<spyOnProperty>:未声明函数可配置

kon*_*ado 6 javascript spy jasmine angularjs webpack-4

我使用 webpack 3 进行了 jasmine 测试。现在我尝试将它与 webpack 4 一起使用,但有一些问题。

首先,我有spyOn功能的问题。

错误:: myFunction 未声明为可写或没有设置器

我找到了一些关于这个问题的解决方法的文章:spy-on-getter-and-setter

我将spyOn更改为spyOnProperty但没有运气。现在我有问题

> 错误:: myFunction 未声明为可配置

我的代码是用 js 编写的,如下所示:

import * as FocusServiceSpy from '../focus/FocusService';

describe('#onLinkClick', function() {
            it('should call myFunction', () => {
                spyOnProperty(FocusServiceSpy, 'myFunction', 'get');
                expect(FocusServiceSpy.myFunction).toHaveBeenCalled();
            });

        }
Run Code Online (Sandbox Code Playgroud)

你知道这可能有什么问题吗?

更新1:

我应该更具描述性。我想创建对FocusService功能的间谍。这个服务只有一个方法叫做myFunction。我唯一想要实现的是确保调用此方法。

现在我把它改成这样,并且有错误:

>TypeError: Object is not a constructor (evaluating 'new FocusService()') (line 180)

describe('#onLinkClick', function() {
        const FocusService = require('../focus/FocusService');

        it('should call myFunction', () => {
            const service = new FocusService();
            spyOnProperty(service, 'myFunction').and.callThrough();
            ... (do some action)
            expect(service.myFunction).toHaveBeenCalled();
        });

    }
Run Code Online (Sandbox Code Playgroud)

FocusService看起来像这样:

export function myFunction(arg) {
    ... (do some action)
}
Run Code Online (Sandbox Code Playgroud)

umi*_*der 7

在你的单元测试中,我可以看到几个问题。首先,您需要了解将属性上的spyOnPropertya 安装spy到现有对象上,但它不会调用其getter本身。

  1. 您不创建对象也不将其提供给spyOnProperty.

  2. 您可以spyOnProperty使用函数名称而不是属性名称进行调用。

您的测试可以构造如下:

it('should call myFunction', () => {

    // given
    const service = new FocusService(); 
    const spy = spyOnProperty(service , 'myProperty', 'get').and.callThrough();

    // when
    const myProperty = service.myProperty; 

    // then
    expect(myProperty).toBe(<expected value>);
    expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)