【问题标题】:Testing with Mocha and Chai consuming values from previous tests使用之前测试中的 Mocha 和 Chai 消耗值进行测试
【发布时间】:2018-12-10 05:48:46
【问题描述】:

我使用TypeScript 使用mochachai 创建了一些测试,它们实际上按预期工作。每个函数都返回一个运行testPromise

我的问题是,如果不使用您在下面看到的嵌套,是否可以在每个 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


    【解决方案1】:

    如果你使用promise,你可以避免这个回调地狱,因为这是promise的主要目的。

    解决问题的一些想法。

    // temp variable to store jwt token
    let token;
    
    registerNonExistingUser(email, pass, role)
      .then((jwtToken: string) => { 
        token = jwtToken; // assign it so other functions can use it
        return authenticateUserCorrectJwt(jwtToken)
      })
      .then((user) => authenticateUserWrongJwt())
      .then(() => loginUserWrongCredentials())
      .then(() => loginUserCorrectCredentials(email, pass))
      .then((jwtToken: string) => getLocalUserInfoCorrectJwt(jwtToken, email))
      .then((user) => createTodoAsEditor(token, todoTitle))
      .then((todos) => checkTodoExistsWithCorrectTitle(token, todoTitle))
      .then((todo: any) => deleteTodoWithCorrectIdAsEditor(token, todo._id))
      .then((todo) => unregisterExistingUser({ 'local.email': email }))
      .then((user) => {
        // console.log(Commons.stringify(user));
      });
    

    或者如果你使用 node 7.6.0 或更高版本,你可以使用 async/await。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

    async function printUser() {    
        try { 
          let jwtToken = await registerNonExistingUser(email, pass, role);
          const user = await authenticateUserCorrectJwt(jwtToken);
    
          await loginUserWrongCredentials();
          jwtToken = await loginUserCorrectCredentials(email, pass);
          const user = await getLocalUserInfoCorrectJwt(jwtToken, email);
          const todos = await createTodoAsEditor(token, todoTitle);
          const todo = await checkTodoExistsWithCorrectTitle(token, todoTitle)
    
          const todo = await deleteTodoWithCorrectIdAsEditor(token, todo._id);
          const user = await unregisterExistingUser({ 'local.email': email });
    
          console.log(Commons.stringify(user));
        } catch (error) {
          // catch error here
        }
    }
    

    【讨论】:

    • 感谢@bhoo-day,您的建议成功了。您对我刚刚在上面的版本中添加的问题有什么建议吗?
    • @davidesp 应该适用于您的 Promise.resolve().then 解决方案。可以用调试器做断点还是在里面加console.log
    • 使用时:Promise.resolve() 我在第一个return 上添加了一个断点,调试器停在那里,但同时测试立即完成。然后当我继续调试时,它不会在第二个return 上停止(我认为执行完成或跳转到最后)。另一方面,如果我使用你的版本,当它在第一个return 停止时,测试还没有完成,我可以继续按F5 以按预期从return 跳转到return。跨度>
    • 也许我们可以尝试使用return Promise.resolve().then 或在mocha mochajs.org/#asynchronous-code 的最后一个函数中使用done()
    • 我刚刚添加了 [EDIT 2] 和一个工作示例。你认为我们可以简化它吗?请检查上面。谢谢!
    猜你喜欢
    • 2017-02-18
    • 2013-04-11
    • 1970-01-01
    • 2023-03-22
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    相关资源
    最近更新 更多