Just trying to follow along with <this> module bas...
# typescript
p
Just trying to follow along with this module based unit testing example and Im getting:
Copy code
Error: Program run without the Pulumi engine available; re-run using the `pulumi` CLI
I think this is because the function I’m testing instantiates a provider?
Copy code
import * as pulumi from '@pulumi/pulumi'
import { assert } from 'chai'

pulumi.runtime.setMocks({
    newResource(args: pulumi.runtime.MockResourceArgs): { id: string; state: any } {
        console.log(args)
        return {
            id: `${args.inputs.name}_id`,
            state: args.inputs,
        }
    },
    call(args: pulumi.runtime.MockCallArgs) {
        console.log(args)
        return args.inputs
    },
})

describe(__dirname, () => {
    let module: typeof import('./azure')

    before(async () => {
        module = await import('./azure')
    })

    describe('minimal', () => {
        it('must have all args passed through', (done) => {
            const minimal = module.AzureMinimal(
                'name',
                {
                    subscriptionId: 'subscription',
                    tenantId: 'tenant',
                },
                {
                    protect: true,
                },
                {
                    aliases: ['urn'],
                },
            )
            pulumi.all([minimal.provider, minimal.protect]).apply(([provider, protect]) => {
                assert.exists(provider)
                assert.isTrue(protect)
                done()
            })
        })
    })
})
Copy code
export function AzureMinimal(
    name: string,
    args: AzureMinimalOptionsArgs,
    opts: CustomResourceOptions,
    providerOptions?: ProviderOptions,
): AzureMinimalOptions {
    const provider = new azure.Provider(
        name,
        {
            subscriptionId: args.subscriptionId,
            tenantId: args.tenantId,
        },
        providerOptions,
    )
    return {
        provider,
        ...opts,
    }
}
s
Do you have the pulumi cli installed?
p
yes
s
How are you invoking the tests? It has to be through the pulumi cli, not with node
p
thats not what the docs say?
Copy code
"test": "mocha -r ts-node/register '**/*.test.ts'",
l
In general, you cannot call any Pulumi functions in unit code unless you wrap your test in
pulumi.runInPulumiStack()
. You shouldn't often need to using Pulumi functions in testable units, so it's not much of an issue.
A ComponentResource shouldn't access Pulumi config, call
getStack()
or
getProject()
, or anything like that. All that stuff should happen in your program and be passed into your ComponentResources. That way, they're testable.
p
interesting, let me give that a go
These are just helpers to build extended component resource options, we don’t usually build providers in code we wish to unit test.