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

Expect on value assigned from promise (Jest unittest)

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

我的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() return 就在承诺得到解决之前。在测试结果之前,您需要等待它解决。您可以 return 来自 postClosingNote 的承诺并等待它在您的测试中解决。

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

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'});
    }
});

使用 async/await 有效:

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