异步似乎不等待等待

时间:2019-06-16 12:54:57

标签: node.js

我将node js和postgres以及chai和mocha用于tdd,现在,当我尝试使用错误的外键更新数据库中的项目时遇到了问题。发生这种情况时,我基本上希望从数据库中获取具有有效值的旧项目。

这是Item类中的更新方法

async update() {
        if (this.description.length === 0) {
            throw new Error("Description can not be deleted");
        }
        try {
            const updateItem = await this.tryUpdate();
            this.copyToThis(updateItem);
        } catch (e) {
            const oldItem = await Item.getById(this.id);
            this.copyToThis(oldItem);

            console.log(this);

            throw new Error("Updating did not work");
        }
    }

这是测试失败


it('should throw an error if you update with wrong category or project id and get the old values from the server', async function () {
            const newProject = "3b4e092e-1dd9-40a5-8357-69696b3e35ba";
            const newCategory = "3cf87368-9499-4af1-9af0-10ccf1e84088";
            const item = await Item.getById(updateId);
            expect(item).to.exist;

            const oldProjectId = item.projectId;
            const oldCategoryId = item.categoryId;

            item.projectId = newProject;
            expect(item.update()).to.be.rejectedWith(Error);

            item.categoryId = newCategory;
            expect(item.update()).to.be.rejectedWith(Error);

            expect(item.categoryId).to.equal(oldCategoryId);
            expect(item.projectId).to.equal(oldProjectId);
        });

这是AssertionError

 -3cf87368-9499-4af1-9af0-10ccf1e84088
 +3cf87368-9499-4af1-9af0-10ccf1e84087

如您所见,该项仍然具有错误的categoryId,而不是服务器中的那个。即使日志中包含正确的项目。

1 个答案:

答案 0 :(得分:1)

我自己解决了

我需要在测试中添加一个等待时间

it('should throw an error if you update with wrong category or project id and get the old values from the server', async function () {
            const newProject = "3b4e092e-1dd9-40a5-8357-69696b3e35ba";
            const newCategory = "3cf87368-9499-4af1-9af0-10ccf1e84088";
            const item = await Item.getById(updateId);
            expect(item).to.exist;

            const oldProjectId = item.projectId;
            const oldCategoryId = item.categoryId;

            item.projectId = newProject;
            await expect(item.update()).to.be.rejectedWith(Error);

            item.categoryId = newCategory;
            await expect(item.update()).to.be.rejectedWith(Error);

            expect(item.categoryId).to.equal(oldCategoryId);
            expect(item.projectId).to.equal(oldProjectId);
        });