为什么不能创建新对象并设置属性?

时间:2018-08-06 19:57:41

标签: typescript jestjs

我正在为TypeScript应用程序编写单元测试,并且无法定义新对象和设置属性。我所有其他不需要对象类的测试都可以正常工作,并且仅在测试期间发生,而在生产方法中使用非常相似的代码时则不会。

  

无法设置未定义的属性'eId'。

Candidate.ts

export class Candidate {
    public eId: string;
    public firstName: string;
    public lastName: string;
    public email: string;
    public address: string;
    public job: {
        title: string,
        eId: string,
    };
}

test.ts

import { Candidate } from '../../../src/api/models/JCandidate';

test('Parse API model to API V2', async (done) => {
    const cController = new CController(cService, log)
    const jCandidate = new Candidate();
    jCandidate.eId = '23423'; //Error here
    jCandidate.email = 'Rogers@test.com';
    jCandidate.address = '123 Test Ave';
    jCandidate.job.eId = '1235';
    jCandidate.job.title = 'Test Job Title';
    jCandidate.firstName = 'Test';
    jCandidate.lastName = 'Name';
    const kCandidate = await cController.parseJCandidateToK(jCandidate);
    expect(kCandidate.name).toBe(jCandidate.firstName + ' ' + jCandidate.lastName);
    expect(kCandidate.jobId).toBe(jCandidate.job.eId);
    done();
});

1 个答案:

答案 0 :(得分:1)

我看不到在您标记的行上如何发生错误,但是我希望在jCandidate.job.eId = '1235;'行上发生错误,因为您从未创建jCandidate.job子对象。尝试更换:

jCandidate.job.eId = '1235';
jCandidate.job.title = 'Test Job Title';

具有:

jCandidate.job = {eId: '1235', title: 'Test Job Title'};