|
| 1 | +import plugin from '@/lib/plugin' |
| 2 | + |
| 3 | +let inject |
| 4 | +let context |
| 5 | +const originalContext = { |
| 6 | + beforeNuxtRender: jest.fn(), |
| 7 | + env: { |
| 8 | + test1: 'foo', |
| 9 | + test2: 'bar' |
| 10 | + }, |
| 11 | + nuxtState: { |
| 12 | + env: {} |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +const expectedEnv = { |
| 17 | + test1: 'foo', // from the config env |
| 18 | + test2: 'baz', // from config env, overwritten by nuxt-env |
| 19 | + test3: 'foobar' // from nuxt-env |
| 20 | +} |
| 21 | + |
| 22 | +beforeEach(() => { |
| 23 | + inject = jest.fn() |
| 24 | + context = { ...originalContext } |
| 25 | +}) |
| 26 | + |
| 27 | +describe('Plugin', () => { |
| 28 | + describe('client side', () => { |
| 29 | + beforeEach(() => { |
| 30 | + context.isClient = true |
| 31 | + plugin(context, inject) |
| 32 | + }) |
| 33 | + |
| 34 | + it('injects the env', () => { |
| 35 | + expect(inject).toHaveBeenCalledWith('env', context.nuxtState.env) |
| 36 | + }) |
| 37 | + }) |
| 38 | + |
| 39 | + describe('server side', () => { |
| 40 | + const reqEnv = { test2: 'baz', test3: 'foobar' } |
| 41 | + |
| 42 | + beforeEach(() => { |
| 43 | + context.isClient = false |
| 44 | + }) |
| 45 | + |
| 46 | + describe('in a normal case', () => { |
| 47 | + beforeEach(() => { |
| 48 | + context.req = { env: reqEnv } |
| 49 | + plugin(context, inject) |
| 50 | + }) |
| 51 | + |
| 52 | + it('injects the env', () => { |
| 53 | + expect(inject).toHaveBeenCalled() |
| 54 | + const { calls: { 0: { 0: calls } } } = inject.mock |
| 55 | + expect(calls).toEqual('env') |
| 56 | + }) |
| 57 | + |
| 58 | + it('merges the two env vars', () => { |
| 59 | + const { calls: { 0: { 1: calls } } } = inject.mock |
| 60 | + expect(calls).toMatchObject(expectedEnv) |
| 61 | + }) |
| 62 | + |
| 63 | + it('calls before render hook with a callback', () => { |
| 64 | + expect(context.beforeNuxtRender).toHaveBeenCalled() |
| 65 | + const { calls: { 0: { 0: hookCallback } } } = context.beforeNuxtRender.mock |
| 66 | + |
| 67 | + expect(hookCallback).toBeInstanceOf(Function) |
| 68 | + }) |
| 69 | + |
| 70 | + it('adds env to nuxtState', () => { |
| 71 | + const { calls: { 0: { 0: hookCallback } } } = context.beforeNuxtRender.mock |
| 72 | + |
| 73 | + hookCallback(context) |
| 74 | + |
| 75 | + expect(context.nuxtState.env).toMatchObject(expectedEnv) |
| 76 | + }) |
| 77 | + }) |
| 78 | + |
| 79 | + describe('with missing dependencies', () => { |
| 80 | + beforeEach(() => { |
| 81 | + delete context.env |
| 82 | + }) |
| 83 | + |
| 84 | + it('has sensible defaults', () => { |
| 85 | + const runPlugin = () => { plugin(context, inject) } |
| 86 | + expect(runPlugin).not.toThrow() |
| 87 | + }) |
| 88 | + }) |
| 89 | + }) |
| 90 | +}) |
0 commit comments