gpt4 book ai didi

javascript - 是否可以在 Jasmine.Js 的 toEqual 中检查多种类型?

转载 作者:数据小太阳 更新时间:2023-10-29 05:02:47 29 4
gpt4 key购买 nike

我是 Jasmine 的新手,遇到过我期望是 String 或 null 的情况。我试图在 toEqual 中执行 or ,但我看到了一些奇怪的结果,这让我相信我正在以错误的方式处理这个问题。处理这种情况的最佳方法是什么?

也许我只是在进行错误的测试。我是否应该放弃用一个测试来测试两种情况的想法?

describe("Jasmine", function () {

//1
it("should be able to handle any(String) || null within toEqual for string", function () {
expect("aString").toEqual(jasmine.any(String) || null);
});

//2
it("should be able to handle any(String) || null within toEqual for null", function () {
expect(null).toEqual(jasmine.any(String) || null);
});

//3
it("should be able to handle null || any(String) within toEqual for string", function () {
expect("aString").toEqual(null || jasmine.any(String));
});

//4
it("should be able to handle null || any(String) within toEqual for null", function () {
expect(null).toEqual(null || jasmine.any(String));
});
});
  1. 通过
  2. Expected null to equal <jasmine.any(function String() { [native code] })>.
  3. 通过
  4. Expected null to equal <jasmine.any(function String() { [native code] })>.

我意识到还有一个 toBeNull(),这可能就是结果如此不稳定的原因,但如果没有“或”链接,我不知道如何合并它。

(运行 Jasmine 1.3.1 修订版 1354556913)

已解决!如果有人感兴趣,下面是完整的解决方案

describe("Jasmine", function () {

beforeEach(function () {
this.addMatchers({

toBeStringOrNull: function () {
var actual = this.actual;

this.message = function () {
return "Expected " + actual + " to be either string or null";
};

return typeof actual === 'string' || actual instanceof String || actual === null;
}

});
});

//1
it("should be able to handle any(String) || null within toEqual for string", function () {
expect("aString").toBeStringOrNull();
});

//2
it("should be able to handle any(String) || null within toEqual for null", function () {
expect(null).toBeStringOrNull();
});

//3
it("should be able to handle null || any(String) within toEqual for string", function () {
expect("aString").toBeStringOrNull();
});

//4
it("should be able to handle null || any(String) within toEqual for null", function () {
expect(null).toBeStringOrNull();
});
});

最佳答案

编写您自己的自定义匹配器:

toBeStringOrNull: function() {
var actual = this.actual;

this.message = function () {
return "Expected " + actual + " to be either string or null";
}

return typeof actual === 'string' || actual instanceof String || actual === null;
}

关于javascript - 是否可以在 Jasmine.Js 的 toEqual 中检查多种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15029971/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com