Google 태그 관리자 맞춤 템플릿용 단위 테스트를 사용하면 템플릿의 기능을 확인할 수 있습니다. 각 템플릿에 대해 태그를 배포하지 않고도
실행할 수 있는 테스트 세트를 만들 수 있으므로 개발 과정에서
템플릿의 동작을 지속적으로 테스트할 수 있습니다. 각 테스트는
샘플 입력 값, 모의 함수 호출, 어설션 코드 동작을 제공할 수 있습니다.
제한사항
단위 테스트는 유효성 검사 규칙을 확인하지 않지만 코드 실행 버튼을 사용하여 유효성 검사를 수동으로 확인할 수 있습니다.
단위 테스트에서 모의 API에 대한 권한 검사는 수행되지 않습니다.
이 가이드에서는 맞춤 템플릿용 단위 테스트를 작성하는 방법을 설명합니다. 이 예시에서는 입력 문자열을 가져와서 해당 문자열의 대문자 버전을
반환하는 변수 템플릿을 만듭니다.
새 변수 템플릿을 만듭니다. 왼쪽 탐색 메뉴에서 템플릿을 클릭하고 변수 템플릿 섹션에서 새로 만들기를 클릭합니다.
필드를 클릭합니다.
필드 추가를 클릭하고 텍스트 입력을 선택합니다. 필드 이름을 text1로 지정하고 표시 이름을 'Text 1'로 설정합니다.
코드 탭에서 기본 코드를 샌드박스 처리된 자바스크립트로 바꿉니다.
let input = data.text1;
return input.toUpperCase();
테스트를 클릭하여 테스트 탭을 엽니다.
테스트 추가를 클릭하고 테스트 이름을 'Untitled test 1'에서 'Handles strings'로 변경합니다.
확장 아이콘(expand_more)을 클릭하여 테스트의 샌드박스 처리된 자바스크립트 편집기를 표시합니다. 코드를 샌드박스 처리된 자바스크립트로 바꿉니다.
//CallrunCodetorunthetemplate's code with a lowercase stringletvariableResult=runCode({text1:'this is a test'});//ValidatethattheresultofrunCodeisanuppercasestring.assertThat(variableResult).isEqualTo('THIS IS A TEST');
이 테스트는 'this is a test' 문자열을 변수에 전달하고 이 변수가 'THIS IS A TEST'의 예상 값을 반환하는지 확인하는 테스트입니다. runCode API는 코드 탭에서 템플릿 코드를 실행하는 데 사용됩니다. runCode의 인수는 데이터 전역으로 사용되는 객체입니다. assertThat API는 대상의 값에 대해 유연하게 어설션하는 데 사용할 수 있는 객체를 반환합니다.
▶ 테스트 실행을 클릭하여 테스트를 실행합니다. 그러면 테스트 결과가 콘솔에 표시됩니다.
▶ 테스트 실행 버튼은 사용 설정된 모든 테스트를 표시된 순서대로 템플릿에서 실행합니다. 순서를 변경하려면 드래그 아이콘(⠿)을 사용합니다. 테스트 이름 왼쪽에 있는 원을 클릭하여 테스트를 일시적으로 사용 설정하거나 중지할 수 있습니다. 단일 테스트를 실행하려면 테스트 위로 마우스를 이동할 때 표시되는 ▶ 버튼을 클릭합니다.
실행된 총 테스트 수와 실패한 테스트 수(있는 경우)가 콘솔에 출력됩니다. 이 경우 하나의 테스트만 실행되었으며 테스트는 통과입니다.
테스트 추가를 다시 클릭하여 두 번째 테스트를 추가합니다. 테스트 이름을 'Untitled test 2'에서 'Handles undefined'로 변경합니다.
테스트를 클릭하여 펼친 후 샌드박스 처리된 자바스크립트 편집기를 표시합니다. 샌드박스 처리된 자바스크립트를 편집기에 입력합니다.
[null,null,["최종 업데이트: 2025-07-25(UTC)"],[[["\u003cp\u003eGoogle Tag Manager uses unit tests to validate custom template functionality before deployment.\u003c/p\u003e\n"],["\u003cp\u003eUnit tests for custom templates utilize sample inputs, mock functions, and assertions to verify code behavior.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003erunCode\u003c/code\u003e API executes the template's code within the test environment, while \u003ccode\u003eassertThat\u003c/code\u003e verifies the output against expected values.\u003c/p\u003e\n"],["\u003cp\u003eThese tests help identify and address potential issues, such as handling undefined or unexpected inputs, before deploying the template.\u003c/p\u003e\n"],["\u003cp\u003eBy creating and running unit tests for your custom templates, you can improve the reliability and stability of your Google Tag Manager implementations.\u003c/p\u003e\n"]]],["Unit tests for Google Tag Manager templates validate functionality by running tests without deployment. You create tests within the template editor under the \"Tests\" tab. Tests use `runCode` to simulate template execution with sample data and `assertThat` to verify results. The process involves creating a template, adding input fields, writing code, and creating tests to handle various inputs. Tests can be run individually or collectively. Limitations are that Unit tests do not check validation rules and permission checks do not happen.\n"],null,["# Tests\n\nUnit tests for Google Tag Manager custom templates help you validate the functionality of your templates. You can create a set of tests for each template\nthat can be run without needing to deploy your tag, which allows you to\ncontinuously test your template's behavior during development. Each test can\nprovide sample input values, mock function calls, and assert code behavior.\n\nLimitations\n-----------\n\n- Unit tests do not check validation rules but you can manually check validation using the **Run Code** button.\n- Permission checks do not happen on mocked APIs in unit tests.\n\nThis guide will walk you through how to write unit tests for your custom template. This example creates a variable template that takes an input string and returns\nthe uppercase version of that string.\n\n1. Create a new variable template. Click **Templates** in the left navigation and click **New** under the **Variable Templates** section.\n\n2. Click **Fields**.\n\n3. Click **Add Field** and select **Text input** . Name the field `text1` and set the display name to *\"Text 1\"*.\n\n4. In the **Code** tab, replace the default code with this sandboxed JavaScript:\n\n let input = data.text1;\n return input.toUpperCase();\n\n5. Click **Tests** to open the testing tab.\n\n6. Click **Add Test** and change the test's name from *\"Untitled test 1\"* to *\"Handles strings\"*.\n\n7. Click on the expand icon (*expand_more*) to reveal the test's sandboxed JavaScript editor. Replace the code with this sandboxed JavaScript:\n\n // Call runCode to run the template's code with a lowercase string\n let variableResult = runCode({text1: 'this is a test'});\n // Validate that the result of runCode is an uppercase string.\n assertThat(variableResult).isEqualTo('THIS IS A TEST');\n\n This test passes the string *`'this is a test'`* to the variable and verifies that the variable returns the expected value of *`'THIS IS A TEST'`* . The [`runCode`](/tag-platform/tag-manager/templates/api#runcode) API is used to run the template code in the **Code** tab. The argument to `runCode` is an object that is used as the data global. The [`assertThat`](/tag-platform/tag-manager/templates/api#assertthat) API returns an object that can be used to fluently make assertions about a subject's value.\n8. Click **▶ Run Tests** to run the test. The output of the test will appear in the Console.\n\n The **▶ Run Tests** button runs all of the enabled tests in the template, in the order shown. To change the order, use the drag icon (⠿). A test can be temporarily enabled or disabled by clicking on the circle to the left of the test name. To run a single test, click the ▶ button that appears when you move the mouse over the test.\n\n The console should print the total number of tests run and the number of tests that failed, if any. In this case, only one test was run and it should pass.\n9. Click **Add Test** again to add a second test. Change the test's name from *\"Untitled test 2\"* to *\"Handles undefined\"*.\n\n10. Click on the test to expand it and reveal the sandboxed JavaScript editor. Enter sandboxed JavaScript in the editor:\n\n let variableResult = runCode({});\n assertThat(variableResult).isEqualTo(undefined);\n\n | **Note:** [`runCode`](/tag-platform/tag-manager/templates/api#runcode) is called with an empty object, which means the value of the `text1` field will be `undefined` in this test case.\n11. Click **▶ Run Tests** to run all of the tests at once. The output of the test will appear in the console.\n\n The *Handles undefined* test should fail. Congratulations, you found a bug!\n12. Click **Code** to go back and edit the template's sandboxed JavaScript code. Update the sandboxed JavaScript as follows:\n\n const getType = require('getType');\n\n let input = data.text1;\n if (getType(input) !== 'string') {\n return input;\n }\n return input.toUpperCase();\n\n The updated code follows the best practice of validating the `input` variable before using it.\n13. Click **Tests** to go back to the list of test cases.\n\n14. Click **▶ Run Tests** to run all of the test cases again. This time the *Handles undefined* test should pass.\n\n15. Click **Save**, and close the Template Editor."]]