我正在尝试找到一种干净的方法来编写集成测试(使用实际资源的 jest 的单元测试)和使用 promise 链的 jest,但我可以理解它。
除了正确嵌套 promise 之外,我也不知道如何解决这两个问题:
- 如何让不同的
expects
被 jest 正确地接受到不同的 promise - 即使有异常,也要始终清理资源
我想链接 4 个函数,类似于 Act - Arrange - Assert 模式。 问题是那些功能对 f.e. 有异步调用。一个数据库,可以有期望。
为了更好地理解这里的一些伪代码,这在我的脑海中是怎样的。这只会让我们更好地理解这个问题。
const setupResources = () => new Promise(resolve => {
//async calls to a database to setup a test
await dynamoDBClient.put(params).promise();
// returns data which are necessary for the other steps
resolve(data);
});
const act = (data) => new Promise(resolve => {
// doing some stuff
const otherdata = {data};
// calling some endpoint asyc
const result = await axios.post(
`https://restapi.com/test`,
JSON.stringify(otherdata),
);
// some expects
expect(result.status).toBe(200);
// again some data which will be needed in the other steps
resolve({someInformation: 'info', data}) ;
});
const assertIt = (data) => {
const prarams = {/*db related data*/}
new Promise(resolve=>{
const dbdata = await dynamoDBClient.get(params).promise();
// some expectation
expect(dbdata).toBe(data.data);
resolve();
})
};
const tearDown = (data) => {
// cleanup of data base trash which should always happen
await dynamoDBClient.delete(data.params).promise();
};
如果有意义的话,实际测试应该遵循这些思路。
it('test',()=>{
return setupResources()
.then(act(data))
.then(assertIt(data))
.finally(teardown(data));
})
最佳答案
async..await
是原始 promise 的替代品,不需要使用 then
。将 new Promise
与现有 promise 一起使用是一种反模式。 async
函数解决的问题之一是需要在 promise 链下可用的数据不需要通过整个链传递,它可以声明为范围内的变量可用于链。
应该是:
const setupResources = async () => {
await dynamoDBClient.put(params).promise();
...
return data;
});
和测试:
it('test', async ()=> {
let data;
try {
data = await setupResources();
...
} finally {
await teardown(data);
}
});
设置和拆卸是 beforeEach
和 afterEach
block 解决的任务。如果需要将它们提取为可重用函数,可以通过上下文对象共享公共(public)数据,如图所示 here .
关于unit-testing - 如何在开 Jest 中链接具有多个异常的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63176679/