【发布时间】:2018-12-10 05:48:46
【问题描述】:
我使用TypeScript 使用mocha 和chai 创建了一些测试,它们实际上按预期工作。每个函数都返回一个运行test 的Promise。
我的问题是,如果不使用您在下面看到的嵌套,是否可以在每个 test 上使用前一个 test 返回的值。
我担心的是,如果我有更多 test 嵌套代码可能会非常烦人
import * as request from 'supertest';
import app from '../src/app';
import { Promise } from 'bluebird';
import * as dateformat from 'dateformat';
import Commons from '../../utils/commons';
import { expect } from 'chai';
...
// all the functions used below are defined over here
...
registerNonExistingUser(email, pass, role).then(
(jwtToken: string) => {
authenticateUserCorrectJwt(jwtToken).then(
(user) => {
authenticateUserWrongJwt().then(
() => {
loginUserWrongCredentials().then(
() => {
loginUserCorrectCredentials(email, pass).then(
(jwtToken: string) => {
getLocalUserInfoCorrectJwt(jwtToken, email).then(
(user) => {
createTodoAsEditor(jwtToken, todoTitle).then(
(todos) => {
checkTodoExistsWithCorrectTitle(jwtToken, todoTitle).then(
(todo: any) => {
deleteTodoWithCorrectIdAsEditor(jwtToken, todo._id).then(
(todo) => {
unregisterExistingUser({
'local.email': email,
}).then(
(user) => {
// console.log(Commons.stringify(user));
}
);
}
);
}
);
}
);
}
);
}
);
}
);
}
);
}
);
}
);
你知道如何美化这个吗?
[编辑 1]
@bhoo-day 建议成功了:
registerNonExistingUser(email, pass, role)
.then((_jwtToken: string) => {
return authenticateUserCorrectJwt(_jwtToken);
})
.then((user) => {
return authenticateUserWrongJwt();
})
...
现在我想知道是否可以将链的开头转换为如下所示(我尝试过但不起作用)。我的目标是将每个函数都放在同一级别,包括第一个函数:
Promise.resolve()
.then(() => {
return registerNonExistingUser(email, pass, role);
})
.then((jwtToken: string) => {
return authenticateUserCorrectJwt(jwtToken);
})
.then((user) => {
return authenticateUserWrongJwt();
})
...
[编辑 2]
我尝试了以下方法,它有效。您对如何简化它有任何想法吗?也许可以使用:Promise.resolve()...?
new Promise((resolve) => {
it('dummy', (done) => { resolve(); return done(); });
})
.then(() => {
return registerNonExistingUser(email, pass, role);
})
.then((_jwtToken: string) => {
return authenticateUserCorrectJwt(_jwtToken);
})
谢谢!
【问题讨论】:
标签: node.js unit-testing typescript mocha.js chai