I'm testing a function that returns an object result like
domainResult = {
domainId: uuidv4,
domainName: string,
groupId: uuidv4,
status: string
}
Within the function, the domainId uuid is generated so my normal method of
await expect(function(args)).to.eventually.become(domainResult)
doesn't work because any placeholder domainId uuid won't match what is actually generated in the function. Is there a way to test the validity of the expected response despite this troublesome property?
One method that works is by setting the promise result to a constant, then testing the constant's individual property values. E.g.
result = await function(args);
expect(result.domainId).to.be.a.uuid('v4');
expect(result.domainName).to.eq('myDomain')
etc
However I'm trying to refactor the code and make it more condensed.
The standard answer for this is mocking. The details here depend on the library you are using for unit testing.
In this example, you would mock the
uuidv4module to return a fixed number during the runtime of this test, which you can then verify. Since you're using JavaScript, here is the documentation for mocking modules in Jest: https://jestjs.io/docs/manual-mocks.Another option would be via dependency injection. This requires you to restructure your code, but can be a powerful tool. e.g. instead of a static function which directly calls to
uuidv4, you might create a wrapper class, which has a member function for generating ids. In your tests, you could replace this function (e.g. by subclassing, or in other scenarios by replacing a instance pointer with a different implementation/mock) and test its output independently of the id generation.