【发布时间】:2019-07-02 17:27:38
【问题描述】:
好的,我的设置有点复杂,但我得到的错误仍然很有趣。
我有一个用于 webdriverio 测试运行程序的 Jasmine 测试套件,其中包含一个在其他地方声明的函数,我将一个类的实例传递给该函数。该函数又包含更多嵌套的 describe- 和 it- 块。
const MyObject = require('./my-object');
const { passObject, myFunction } = require('./obj-fns');
var myObjectInstance;
describe("testing passing objects as parameters", function() {
beforeAll(function() {
myObjectInstance = new MyObject();
});
it("for a class instance inside describe/it block directly", function() {
browser.pause(250);
expect(myObjectInstance).not.toBe(undefined);
expect(myObjectInstance.selector).toBe("object-class-instance");
});
it("for a function inside describe/it block directly", function() {
browser.pause(250);
expect(myFunction).not.toBe(undefined);
expect(myFunction().selector).toBe("object-function");
});
passObject(myFunction, myObjectInstance);
});
my-object.js
class MyObject {
constructor() {
this.selector = "object-class-instance";
}
}
module.exports = MyObject;
obj-fns.js
module.exports.passObject = function(fn, obj) {
describe("inside a function that has a describe block", function() {
it("and an it block for a class instance", function() {
browser.pause(250);
expect(obj).not.toBe(undefined);
expect(obj.selector).toBe("object-class-instance");
});
it("and an it block for a function", function() {
browser.pause(250);
expect(fn).not.toBe(undefined);
expect(fn().selector).toBe("object-function");
})
});
}
module.exports.myFunction = function() {
return {
selector: "object-function"
}
}
所有测试都通过,除了 passObject 函数内的 it 块检查对象(已传递的类实例)是否未定义。
pass: testing passing objects as parameters for a class instance inside describe/it block directly
pass: testing passing objects as parameters for a function inside describe/it block directly
pass: testing passing objects as parameters inside a function that has a describe block and an it block for a function
fail: testing passing objects as parameters inside a function that has a describe block and an it block for a class instance (chrome_undefinedVersion with 0-0 runner)
Error: Expected undefined not to be undefined.
at <Jasmine>
at UserContext.<anonymous> (C:\dev\eclipse-workspace\FrontendTesting\Daimler.Van.SPP.Dashboard.Web.FrontendTesting\spec\obj-fns.js:6:29)
at <Jasmine>
这是否符合设计,如果是,如何将类实例传递给具有描述块和它块的函数?还是我错过了什么?
【问题讨论】:
-
您在
describe块内调用passObject(myFunction, myObjectInstance);,但这并不意味着beforeAll被执行。除非我弄错了这应该被视为一个正常的函数调用,所以它只会在没有与其他测试相同的上下文的情况下运行,即beforeAll执行和初始化myObjectInstance = new MyObject();编辑:实际上,我是在这里有点愚蠢 -obj只被使用一次,那是在beforeAll之前执行passObject(myFunction, myObjectInstance);时 - 那时没有为变量分配任何东西。 -
是的,Jasmine 似乎执行了该函数,因此在执行
beforeAll()s 和it()s 之前,在其上下文中将undefined传递为myObjectInstance。如果我将对passObject的调用包装在describe()块中,它也会这样做。 -
我查看了一些 Jasmine 文档,但找不到一个好的 Jasmine 方式来做你想做的事。我会建议您改用“普通 JS”解决方案。我将在答案中概述这一点。如果有更熟悉 Jasmine 的人出现,他们可能会在这里有更合适的解决方案。
标签: javascript jasmine