RxLua/tests/reduce.lua

41 lines
1.7 KiB
Lua

describe('reduce', function()
it('fails if the first argument is not a function', function()
local observable = Rx.Observable.of(0)
expect(observable:reduce()).to.fail()
expect(observable:reduce(1)).to.fail()
expect(observable:reduce('')).to.fail()
expect(observable:reduce({})).to.fail()
expect(observable:reduce(true)).to.fail()
end)
it('uses the seed as the initial value to the accumulator', function()
local accumulator = spy()
Rx.Observable.of(3):reduce(accumulator, 4):subscribe()
expect(accumulator[1]).to.equal({4, 3})
end)
it('waits for 2 values before accumulating if the seed is nil', function()
local accumulator = spy(function(x, y) return x * y end)
local observable = Rx.Observable.fromTable({2, 4, 6}, ipairs):reduce(accumulator)
expect(observable).to.produce(48)
expect(accumulator).to.equal({{2, 4}, {8, 6}})
end)
it('uses the return value of the accumulator as the next input to the accumulator', function()
local accumulator = spy(function(x, y) return x + y end)
local observable = Rx.Observable.fromTable({1, 2, 3}, ipairs):reduce(accumulator, 0)
expect(observable).to.produce(6)
expect(accumulator).to.equal({{0, 1}, {1, 2}, {3, 3}})
end)
it('passes all produced values to the accumulator', function()
local accumulator = spy(function() return 0 end)
local observable = Rx.Observable.fromTable({2, 3, 4}, ipairs, true):reduce(accumulator, 0):subscribe()
expect(accumulator).to.equal({{0, 2, 1}, {0, 3, 2}, {0, 4, 3}})
end)
it('calls onError if the accumulator errors', function()
expect(Rx.Observable.fromRange(3):reduce(error)).to.produce.error()
end)
end)