如何在 Jasmine 中测试柯里化函数的结果?
How to test the result of a curried function in Jasmine?
用例:
- 我有一个功能模块,每个功能都经过单元测试
- 我有一个工厂函数可以创建第三方库所需的这些函数流。
- 我想测试一下这个工厂函数是否生成了正确的流。使用
@cycle/Time
,我能够创建流并在流上断言。
- 我能够断言函数以正确的顺序出现在流中。
- 但是,我无法断言任何柯里化函数。如何断言柯里化函数?
- 目前,我有一个 hack 到
JSON.stringify
函数并断言它们的来源。
为了简化问题,我创建了一个简单的测试套件,因此我们不关心使用 @cycle/Time
。柯里化函数似乎是该函数的新实例。请看下面的代码。
我想知道我怎样才能让失败的测试通过?在这种情况下,我使用 bind
来模拟 curried 函数。这可能吗?
const a = () => b
const b = () => {}
const c = (arg) => b.bind(null, arg)
const d = () => () => {}
describe("curried function test", function() {
it('should return a reference to b', () => {
expect(a()).toBe(b)
})
// This test fails because b.bind returns a new function.
it('should return a reference to a curried b', () => {
expect(c('foo')).toBe(b)
})
it('should create a new instance everytime', () => {
expect(d()).not.toBe(d())
})
});
我已经设置了一个 jsfiddle here。
"This test fails because b.bind
returns a new function."
那是因为你从 c
得到的结果是 b.bind(null, arg)
的结果,这与 b
不同。
否则,b.bind
将是 修改 b
.
正如 mdn 所说:
The bind()
method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
(source, emphasis mine)
基本上,c
不能 return 引用 b
.
你做的是结果函数的名称:
const b = () => {};
const c = (arg) => b.bind(null, arg);
const e = c("foo");
console.log(e.name);
console.log(e.name === `bound ${b.name}`);
因此,您可以测试 e.name
等于 "bound " + b.name
。
用例:
- 我有一个功能模块,每个功能都经过单元测试
- 我有一个工厂函数可以创建第三方库所需的这些函数流。
- 我想测试一下这个工厂函数是否生成了正确的流。使用
@cycle/Time
,我能够创建流并在流上断言。 - 我能够断言函数以正确的顺序出现在流中。
- 但是,我无法断言任何柯里化函数。如何断言柯里化函数?
- 目前,我有一个 hack 到
JSON.stringify
函数并断言它们的来源。
为了简化问题,我创建了一个简单的测试套件,因此我们不关心使用 @cycle/Time
。柯里化函数似乎是该函数的新实例。请看下面的代码。
我想知道我怎样才能让失败的测试通过?在这种情况下,我使用 bind
来模拟 curried 函数。这可能吗?
const a = () => b
const b = () => {}
const c = (arg) => b.bind(null, arg)
const d = () => () => {}
describe("curried function test", function() {
it('should return a reference to b', () => {
expect(a()).toBe(b)
})
// This test fails because b.bind returns a new function.
it('should return a reference to a curried b', () => {
expect(c('foo')).toBe(b)
})
it('should create a new instance everytime', () => {
expect(d()).not.toBe(d())
})
});
我已经设置了一个 jsfiddle here。
"This test fails because
b.bind
returns a new function."
那是因为你从 c
得到的结果是 b.bind(null, arg)
的结果,这与 b
不同。
否则,b.bind
将是 修改 b
.
正如 mdn 所说:
The
bind()
method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
(source, emphasis mine)
基本上,c
不能 return 引用 b
.
你做的是结果函数的名称:
const b = () => {};
const c = (arg) => b.bind(null, arg);
const e = c("foo");
console.log(e.name);
console.log(e.name === `bound ${b.name}`);
因此,您可以测试 e.name
等于 "bound " + b.name
。