简体   繁体   中英

Avoid warnings when using jest to test that data corresponds to TypeScript types

In the example below I want to verify that the data actually gives med a project with a property id .

test('getActiveProject => Project', async () => {
    let previouslyOpenProject = await client.getActiveProject()
    if (!previouslyOpenProject) {
        previouslyOpenProject = await client.createProject();
    }
    let project = await client.getActiveProject();
    expect(project.id).toBeGreaterThanOrEqual(1);
});

I get the following ts error message

[ts] Object is possibly 'null' (referring to project and the use of project.id)

What is a good course of action from here:

  • Should I write my tests in js instead of ts?
  • Should I find a testing framework with a TypeScript pre-processor that will allow me to use TypeScript types in test expectations? (I don't think this exists)
  • Should these kinds of checks be made by some kind of json validation scheme instead of jest tests?

Result type fo getActiveProject is Project | null Project | null . If you are sure that let project is not null you can map it by let project = await client.getActiveProject() as Project; .

Also you can do something like this

let project = await client.getActiveProject(); // without type mapping
if (project !== null) {
  // here project will be Project type, not a Project | null
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM