【问题标题】:Jasmine : Spying an exported function that is called by an another function doesn't workJasmine:监视由另一个函数调用的导出函数不起作用
【发布时间】:2019-11-25 14:47:47
【问题描述】:

我已经创建了 2 个辅助函数,其中一个是第一个的快捷方式,在我的测试中我想验证这个函数是否被调用,这些函数在同一个文件中:

export function test1(param1, param2, param3, param4) {
    return { param1, param2, ...(param3 && { param3 }), ...(param4 && { param4 }) };
}

export function test2(param1, param2) {
    return test1(param1, null, null, param2);
}

在测试中我需要证明第一个是由第二个调用的:

import * as Util from './my-util-file';
const test2 = Util.test2;
...
it('should call test1 when test2 is called', () => {
    const test1 = spyOn(Util, 'test1').and.callThrough();
    test2('test', 1);
    expect(test1).toHaveBeenCalledWith('test', null, null, 1);
});

或者

import {test1, test2} from './my-util-file';
...
it('should call test1 when test2 is called', () => {
    const test1Spy = jasmine.createSpy('test1');
    test2('test', 1);
    expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});

或者

import * as Util from './my-util-file';
const test2 = Util.test2;

...
it('should call test1 when test2 is called', () => {
    const test1Spy = spyOnProperty(Util, 'test1');
    test2('test', 1);
    expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});

或者

import {test1, test2} from './my-util-file';

...
it('should call test1 when test2 is called', () => {
    const test1Spy = spyOn(window as any, 'test1');
    test2('test', 1);
    expect(test1Spy).toHaveBeenCalledWith('test', null, null, 1);
});

但问题是我得到了错误:

预期的 spy test1 已被调用。

【问题讨论】:

  • 我认为这可能与您导入Util 文件的方式有关。您可以尝试正常导入这两个功能吗? import {test1, test2} from './my-util-file';
  • 我也试过了,还是一样的错误

标签: angular typescript jasmine karma-jasmine


【解决方案1】:

这不是茉莉花的问题。这就是 javascript 模块在编译/转译时的行为方式。

var test1 = function test1() {};
var test2 = function test2() { test1(); };

exports.test1 = test1;
exports.test2 = test2;

当函数test2被声明时,对test1函数的引用被包含在函数声明中。但在规范中,我们真正导入的是exports.test1 && exports.test2。所以基本上我们是在监视一些无意的东西,即exports.test1。

所以为了保持引用,我们可以定义和导出测试函数如下:

const test1 = function(param1: any, param2: any, param3: any, param4: any) {
  return { 
    param1,
    param2,
    ...(param3 && { param3 }),
    ...(param4 && { param4 })
  };
};

const test2 = function(param1: any, param2: any) { 
  return testFunctions.test1(param1, null, null, param2); //Here we are attaching the refernce
};

export const testFunctions = {
  test1,
  test2
};

我们可以如下测试它们:

import * as test from './test';

const functions = test.testFunctions;

it('should call test1 when test2 is called', () => {
    const test1 = spyOn(functions, 'test1').and.callThrough();
    functions.test2('test', 1);
    expect(test1).toHaveBeenCalledWith('test', null, null, 1);
});

一个很好的article 解释了上述问题供您参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多