如何在另一个方法中创建的对象上使用 Jasmine 间

How to use Jasmine spies on an object created inside another method?(如何在另一个方法中创建的对象上使用 Jasmine 间谍?)
本文介绍了如何在另一个方法中创建的对象上使用 Jasmine 间谍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下代码片段,您将如何创建 Jasmine spyOn 测试以确认 doSomething 在您运行 MyFunction 时被调用?

Given the following code snippet, how would you create a Jasmine spyOn test to confirm that doSomething gets called when you run MyFunction?

function MyFunction() {
    var foo = new MyCoolObject();
    foo.doSomething();
};

这是我的测试的样子.不幸的是,在评估 spyOn 调用时出现错误:

Here's what my test looks like. Unfortunately, I get an error when the spyOn call is evaluated:

describe("MyFunction", function () {
    it("calls doSomething", function () {

        spyOn(MyCoolObject, "doSomething");
        MyFunction();
        expect(MyCoolObject.doSomething).toHaveBeenCalled();

    });
});

Jasmine 此时似乎无法识别 doSomething 方法.有什么建议吗?

Jasmine doesn't appear to recognize the doSomething method at that point. Any suggestions?

推荐答案

当您调用 new MyCoolObject() 时,您会调用 MyCoolObject 函数并使用相关原型.这意味着当您 spyOn(MyCoolObject, "doSomething") 时,您不是在 new 调用返回的对象上设置间谍,而是在可能的 MyCoolObject 函数本身的>doSomething 函数.

When you call new MyCoolObject() you invoke the MyCoolObject function and get a new object with the related prototype. This means that when you spyOn(MyCoolObject, "doSomething") you're not setting up a spy on the object returned by the new call, but on a possible doSomething function on the MyCoolObject function itself.

您应该能够执行以下操作:

You should be able to do something like:

it("calls doSomething", function() {
  var originalConstructor = MyCoolObject,
      spiedObj;
  spyOn(window, 'MyCoolObject').and.callFake(function() {
    spiedObj = new originalConstructor();
    spyOn(spiedObj, 'doSomething');
    return spiedObj;
  });
  MyFunction();
  expect(spiedObj.doSomething).toHaveBeenCalled();
});

这篇关于如何在另一个方法中创建的对象上使用 Jasmine 间谍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)