Testdouble的用法当没有在td.object中被调用时



可能是我对Testdouble的误解,但是我创建了这个例子来说明我遇到的问题:

const test = require("ava");
const td = require("testdouble");
const reducer = async (state, event) => {
if (event.id === "123") {
const existing = await state.foo("", event.id);
console.log("existing:", existing);
}
};
test("foo", async (t) => {
const foo = td.func(".foo");
const state = td.object({
foo
});
td.when(foo(td.matchers.anything(), td.matchers.anything())).thenResolve({
id: "123"
});
await reducer(state, {
id: "123",
nickname: "foo"
});
});

此日志:existing: undefined

而我认为它应该log:existing: { id: "123" }td.when()所述

我错过了什么?

我认为你的问题是td.object不像你认为的那样工作:

td.object(realObject)-返回传递对象的深度模仿,其中每个函数被替换为以属性路径命名的测试双精度函数(例如,如果realObject.invoices.send()是一个函数,返回的对象将把属性invoices.send设置为名为'.invoices.send'的测试双精度函数)

来源:https://github.com/testdouble/testdouble.js tdobject

所以当你…

const foo = td.func();
const obj = td.object({foo});

…你居然嘲笑了foo两次。

下面是一个示例:

const td = require('testdouble');
const num2str = td.func('num->string');
td.when(num2str(42)).thenReturn('forty two');
td.when(num2str(43)).thenReturn('forty three');
td.when(num2str(44)).thenReturn('forty four');
const x = {num2str};
const y = td.object({num2str});
num2str(42);
x.num2str(43);
y.num2str(44);

然后我们可以检查x.num2str,我们可以看到它是相同的测试和num2str:

td.explain(x.num2str).description;
/*
This test double `num->string` has 3 stubbings and 2 invocations.
Stubbings:
- when called with `(42)`, then return `"forty two"`.
- when called with `(43)`, then return `"forty three"`.
- when called with `(44)`, then return `"forty four"`.
Invocations:
- called with `(42)`.
- called with `(43)`.
*/

然而y.num2str是一个完全不同的测试double:

td.explain(y.num2str).description;
/*
This test double `.num2str` has 0 stubbings and 1 invocations.
Invocations:
- called with `(44)`.
*/

我想你要找的是"属性替换"。td.replace的行为:

const z = {
str2num: str => parseInt(str),
num2str: num => {
throw new Error('42!');
}
};
td.replace(z, 'num2str');
td.when(z.num2str(42)).thenReturn('FORTY TWO!!');

z.str2num函数没有被模拟:

z.str2num("42");
//=> 42

然而z.num2str是一个完全成熟的测试替身:

z.num2str(42);
//=> 'FORTY TWO!!'
td.explain(z.num2str).description;
/*
This test double `num2str` has 1 stubbings and 1 invocations.
Stubbings:
- when called with `(42)`, then return `"FORTY TWO!!"`.
Invocations:
- called with `(42)`.
*/

最新更新