gpt4 book ai didi

javascript - 期望从 promise 分配的值(Jest unittest)

转载 作者:行者123 更新时间:2023-11-29 22:45:08 26 4
gpt4 key购买 nike

我正在对 es6 类进行单元测试,并希望我的测试能够验证写入类变量的值。

我的类(class)有以下方法:

export default class ctrl{
constructor(){}

postClosingNote(payload) {
this._headerNoteService.createNewNote(payload).then(data => {
this.note = {};
this.claimNotes = data;
this.returnToClaimHeader();
});
}
}

服务方式:

createNewNote(postData){
return this._http.post(`${api}`, postData).then(res => res.data);
}

单元测试:

    beforeEach(() => {
when(headerNoteService.createNewNote).calledWith(newNote).mockReturnValue(Promise.resolve({'claimNotes': 'txt'}));
});

const newNote = {
text: "txt",
claimDescriptionTypeId: 4,
claimHeaderId: headerId
};

test('Confirm that newly submitted note is added to the headers notes', () => {
target = new ctrl();
target.postClosingNote(newNote);
expect(target.claimNotes).toEqual({'claimNotes': 'txt'});
});

运行测试的输出:

Expected value to equal:
{"claimNotes": "txt"}
Received:
undefined

控制台的日志记录目标不包括对 this.notethis.claimNotes 的任何引用

最佳答案

我相信这是因为 postClosingNote() 在 promise 解决之前立即返回。在测试结果之前,您需要等待它解决。您可以从 postClosingNote 返回 promise 并等待它在您的测试中解析。

(还没有实际运行这段代码,可能有语法错误,但你明白了):

postClosingNote(payload) {
return this._headerNoteService.createNewNote(payload).then(data => {
this.note = {};
this.claimNotes = data;
this.returnToClaimHeader();
});
}

单元测试:

test('Confirm that newly submitted note is added to the headers notes', () => {
target = new ctrl();
target.postClosingNote(newNote).then(result => {
expect(target.claimNotes).toEqual({'claimNotes': 'txt'});
}
});

关于javascript - 期望从 promise 分配的值(Jest unittest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58918328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com