简体   繁体   English

使用 Jasmine 在 TypeScript 中监视没有对象的非导入函数

[英]Using Jasmine to spy on a non-imported function without an object in TypeScript

I understand what's going on in: Using Jasmine to spy on a function without an object and why it doesn't work in TypeScript.我了解发生了什么: 使用 Jasmine 监视没有对象的函数以及为什么它在 TypeScript 中不起作用。 I also see this TypeScript answer: https://stackoverflow.com/a/43532075/2548010 .我也看到了这个 TypeScript 答案: https : //stackoverflow.com/a/43532075/2548010

Unfortunately this only solves the case for imported spied on functions.不幸的是,这只能解决导入的监视函数的情况。 I am testing a function that takes in a function, and I am trying to see that the passed in function is called with the correct parameters.我正在测试一个接受函数的函数,我试图查看传入的函数是否使用正确的参数调用。

import { chowDown } from './file.ts';

interface Taco {
  filling: string;
  hasCheese: boolean;
  isCrispy: boolean;
}

describe('chowdown', () => {
  const eatTaco = (taco: Taco) => {};
  const expectedTaco = {filling: 'ground beef', hasCheese: false, isCrispy: true};

  it('eats the taco', () => {
    chowdown(eatTaco);
    expect(eatTaco).toHaveBeenCalledWith(expectedTaco);
  });
});

What I would like to do is something like我想做的是类似的事情

spyOn(eatTaco);
//or
spyOn(window, 'eatTaco');

None of the proposed solutions that I have found online actually work for this infrequent spy event.我在网上找到的所有建议解决方案都不适用于这种罕见的间谍事件。 Does anyone have any ideas as to how to actually spy on eatTaco properly?有没有人对如何正确监视eatTaco有任何想法?

Thanks谢谢

Replace the eatTaco function with the following spy:用以下 spy 替换eatTaco函数:

const eatTaco = jasmine.createSpy<(taco: Taco) => void>();

This TypeScript generics keeps you type safe.这个 TypeScript 泛型让你的类型安全。

Okay, I figured it out.好吧,我想通了。

The declaration of eatTaco had to change from this: eatTaco的声明不得不从这个改变:

  const eatTaco = (taco: Taco) => {};

to this:对此:

  const eatTaco = jasmine.createSpy();

This still works with TypeScript and Jasmine is smart enough to properly handle toHaveBeenCalledWith(...) without the typings.这仍然适用于 TypeScript,而且 Jasmine 足够聪明,可以在没有类型的情况下正确处理toHaveBeenCalledWith(...) You do lose a bit of type safety here, but as long as you have the type declared in the actual code - your test doesn't technically need it.您确实在这里失去了一些类型安全性,但是只要您在实际代码中声明了类型 - 您的测试在技术上不需要它。

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

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