24

If I have a plain-old JavaScript object and a TypeScript interface, how can I write a test that asserts object conforming to my interface?

interface Person {
  name: string
  age?: number
}

describe('Person interface check', () => {
  it ('should conform to "Person" interface', () => {
     let obj1 = {name: "Mohsen"};
     let obj2 = {name: "Hommer", age: 40};

     expect(obj1) // ????
  });
});

EDIT: I don't want to do deep assertion, eg expect(obj1.name).to.be.a.string

2

3 Answers 3

11

asserts object conforming to my interface

You have to do it manually:

expect(typeof object.name).to.eql("string");
// so on 

Update : Writing code to do the deep assertion for you

Since the type information TypeScript sees is removed in the generated JS you don't have access to the type information in js. However you can write code to take the TS view of the code (using the typescript language service) and generate the JS code that does these deep assertions for you.

Sign up to request clarification or add additional context in comments.

1 Comment

sadly its not easy yet
4

I just had the same problem and my solution was to build a json schema of my interface.
You can use an automated tool to built it for you by passing your custom interface like this:

typescript-json-schema "./myfile.ts" MyCustomType --strictNullChecks --noExtraProps --required --out=output.json

Then, you can use the extension jest-json-schema to check if your object matches your generated schema like this:

const mySchema = require('path/to/output.json')
expect(myStrangeObject).toMatchSchema(mySchema)

This worked like a charm for me.

(I'd recommend getting familiar with json schema keywords because those flags "--strictNullChecks --noExtraProps --required" makes a big difference when generating the schema depending on your interface definition)

Comments

1

There are a number of different packages that would allow you to test this at "typecheck" time.

Here's an example using one that I wrote: https://tsplay.dev/oN94ow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.