通过Jest测试TypeScript服务器运行时代码 #

本指南介绍如何使用流行的JestJavaScript测试框架为TypeScript服务器运行时代码配置和编写测试。

为代码编写测试可以确保代码的行为符合预期,并且可以安全地防范您在未来意外地做出破坏性更改。

配置Jest的TypeScript服务器项目 #

为编写Jest测试,您需要安装一些不同的包。

1
npm i -D jest @types/jest ts-jest ts-auto-mock jest-ts-automock ttypescript

tsconfig.json文件中,将以下内容添加到compilerOptions部分:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
  "compilerOptions": {
    "plugins": [
      {
        "transform": "ts-auto-mock/transformer",
        "cacheBetweenTests": false
      }
    ]
  }
}

package.json中,添加新的"test"脚本:

1
2
3
4
5
{
  "scripts": {
    "test": "jest"
  }
}

还为"jest"添加一个新的部分:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
  "jest": {
    "globals": {
      "ts-jest": {
        "compiler": "ttypescript"
      }
    },
    "transform": {
      ".(ts|tsx)": "ts-jest"
    },
    "setupFiles": [
      "<rootDir>jest-config.ts"
    ]
  }
}

最后,在项目根目录(或您的配置中的"setupFiles"部分指定的路径)下创建jest-config.ts

1
import 'jest-ts-auto-mock';

编写可测试RPC #

这是一个示例性RPC,玩家可调用它将物品添加到自己的库存中。本例中的库存是Nakama存储引擎中的一个条目。

代码将检查传入的有效负载,以确保其符合特定条件,并且在所有潜在的故障点,RPC将记录错误并向用户返回相应的故障响应。

创建一个名为 rpc-add-item.ts 的文件。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const AddItemRpc = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, payload: string): string {
  // Define success and failure responses.
  const success = JSON.stringify({ success: true });
  const failure = function(error: string) {
      logger.error(error);
      return JSON.stringify({
          success: false,
          error
      })
  };

  // If the payload is empty, return a failure.
  if (!payload || payload === "") {
      return failure("no payload provided");
  }

  const itemToAdd = JSON.parse(payload);

  // If the payload contains no item name, return a failure.
  if (!itemToAdd.name) {
      return failure("item has no name");
  }

  // If the payload contains no quantity, or a non-numeric quantity, return a failure.
  if (!itemToAdd.quantity || isNaN(Number(itemToAdd.quantity))) {
      return failure("item has no quantity");
  }

  // If the payload quantity is negative, return a failure.
  if (itemToAdd.quantity <= 0) {
      return failure("quantity provided must be greater than 0");
  }

  // Define a storage read request to get the player's current inventory.
  const readRequest: nkruntime.StorageReadRequest = {
      collection: "player",
      key: "inventory",
      userId: ctx.userId
  };

  let inventory = {};

  // Attempt to get the player's current inventory from storage.
  const result = nk.storageRead([readRequest]);
  if (result.length > 0) {
      inventory = result[0].value;
  }

  // If the player already has the item, increase the quantity, otherwise add it.
  if (inventory[itemToAdd.name]) {
    inventory[itemToAdd.name] += itemToAdd.quantity;
  } else {
    inventory[itemToAdd.name] = itemToAdd.quantity;
  }

  // Define the storage write request to update the player's inventory.
  const writeRequest: nkruntime.StorageWriteRequest = {
      collection: "player",
      key: "inventory",
      userId: ctx.userId,
      permissionWrite: 1,
      permissionRead: 1,
      value: inventory
  };

  // Write the updated inventory to storage.
  const storageWriteAck = nk.storageWrite([writeRequest]);

  // Return a failure if the write does not succeed.
  if (!storageWriteAck || storageWriteAck.length == 0) {
      return failure("error saving inventory");
  }

  return success;
}

export default AddItemRpc;

编写第一个测试 #

用以下导入创建名为rpc-add-item.test.ts的文件。

1
2
3
import { createMock } from 'ts-auto-mock';
import { On, method } from 'ts-auto-mock/extension';
import AddItemRpc from "../rpc-add-item";

这些导入可让您创建Nakama服务器运行时类型和函数的模拟。您可以在独立的和精心设计的场景下测试代码,而无需与Nakama进行交互。

创建describe块,使您能够将相关测试组合到一起。在内部,为我们调用RPC所需的各种模拟对象定义变量。

1
2
3
4
5
describe('AddItemRpc', function() {
  let mockCtx, mockLogger, mockNk, mockLoggerError, mockNkStorageRead, mockNkStorageWrite, mockStorageWriteAck;

  // Further code goes here
});

接下来创建beforeEach块。传入的函数将在每次测试前运行。如果您需要在测试前进行一些设置,这将很有帮助。此处您将使用它来配置前面定义的模拟对象。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
beforeEach(function () {
    // Create mock objects to pass to the RPC.
    mockCtx = createMock<nkruntime.Context>({ userId: 'mock-user' });
    mockLogger = createMock<nkruntime.Logger>();
    mockNk = createMock<nkruntime.Nakama>();
    mockStorageWriteAck = createMock<nkruntime.StorageWriteAck>();

    // Configure specific mock functions to use Jest spies via jest-ts-auto-mock
    mockLoggerError = On(mockLogger).get(method(function (mock) {
        return mock.error;
    }))
    mockNkStorageRead = On(mockNk).get(method(function (mock) {
        return mock.storageRead;
    }));
    mockNkStorageWrite = On(mockNk).get(method(function (mock) {
        return mock.storageWrite;
    }));
});

createMock函数使用<>语法获取通用类型,以确定模拟的类型。然后,它将继续为该类型的所有属性创建一个具有默认值/空值的对象。您可以通过将对象传递到函数中来覆盖特定的属性值,例如上面的userId属性。

您会发现已经配置了3个特定函数来充当Jest模拟函数(使用通过ts-auto-mock/extension提供的On函数):logger.errornk.storageReadnk.storageWrite。 这样,您就可以根据测试场景验证是否使用特定值调用了这些函数。

现在您将编写您的第一个测试。此测试将进行检查,以确保RPC在传递给它的有效负载为null时返回带有特定错误消息的故障响应。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
test('returns failure if payload is null', function() {
    const payload = null;
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'no payload provided';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
});

此处:

  • 调用AddItemRpc函数,传入定义的模拟对象和有效负载的null
  • 获取作为JSON对象的结果,通过使用: JSON.parse
  • 定义预期的错误响应字符串

然后您使用expect函数验证:

  • resultPayload.success 值是 false
  • resultPayload.error 值是预期的错误字符串 'no payload provided'
  • logger.error 通过同样的错误信息调用函数

运行测试:

1
npm run test

如果运行这个测试,应该看到它通过了。

您可以通过将expectedError值更改为其他值并重新运行测试来验证此测试是否确实有效。例如,将此值更改为'payload provided',将导致以下Jest输出。

1
2
3
4
Error: expect(received).toBe(expected) // Object.is equality

Expected: "payload provided"
Received: "no payload provided"

模拟Nakama函数的返回值 #

通常在编写测试时,您需要模拟特定函数的返回值,以改变被测试代码的结果。借助Jest,这可以通过使用各种mockReturnValue函数实现。

在以下测试中,在mockNkStorageWrite(作为jest.Mock类型)函数上使用了mockReturnValueOnce函数,以强制返回null。而这意味着AddItemRpc函数应当发生故障,并返回故障响应。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
test('returns failure if nk.storageWrite returns null', function () {
  (mockNkStorageWrite as jest.Mock).mockReturnValueOnce(null);

  const payload = JSON.stringify({
    name: 'Diamond Pickaxe',
    quantity: 1
  });
  const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
  const resultPayload = JSON.parse(result);
  const expectedError = 'error saving inventory';

  expect(resultPayload.success).toBe(false);
  expect(resultPayload.error).toBe(expectedError);
  expect(mockLoggerError).toBeCalledWith(expectedError);
});

mockReturnValueOnce函数可用于从模拟函数返回任何值,因此可用于完全改变测试结果。

考虑以下两个示例:

1
(mockNkStorageRead as jest.Mock).mockReturnValueOnce({});
1
2
3
4
5
6
7
(mockNkStorageRead as jest.Mock).mockReturnValueOnce([
  {
    value: {
      'Diamond Pickaxe': 3
    }
  }
]);

在第一种情况下,nk.storageRead调用的响应被模拟为不返回结果,有效地模拟了Nakama的响应,即指定的集合、键和用户不存在存储对象。

第二个返回一个包含单个对象的数组,表示玩家当前的库存中包含3个钻石镐。

这有助于您在玩家库存处于不同状态时,测试RPC的行为方式。

完整示例 #

以下为rpc-add-item.test.ts文件的完整代码,涵盖各种不同的成功与失败情景。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import { createMock } from 'ts-auto-mock';
import { On, method } from 'ts-auto-mock/extension';
import AddItemRpc from "../rpc-add-item";

describe('AddItemRpc', function () {
  let mockCtx, mockLogger, mockNk, mockLoggerError, mockNkStorageRead, mockNkStorageWrite, mockStorageWriteAck;

  beforeEach(function () {
    mockCtx = createMock<nkruntime.Context>({ userId: 'mock-user' });
    mockLogger = createMock<nkruntime.Logger>();
    mockNk = createMock<nkruntime.Nakama>();
    mockStorageWriteAck = createMock<nkruntime.StorageWriteAck>();
    mockLoggerError = On(mockLogger).get(method(function (mock) {
      return mock.error;
    }))
    mockNkStorageRead = On(mockNk).get(method(function (mock) {
      return mock.storageRead;
    }));
    mockNkStorageWrite = On(mockNk).get(method(function (mock) {
      return mock.storageWrite;
    }));
  });

  test('returns failure if payload is null', function () {
    const payload = null;
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'no payload provided';


    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if payload is empty string', function () {
    const payload = "";
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'no payload provided';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if payload is empty JSON object', function () {
    const payload = JSON.stringify({});
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'item has no name';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if payload has no quantity', function () {
    const payload = JSON.stringify({
      name: 'Diamond Pickaxe'
    });
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'item has no quantity';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if payload has 0 quantity', function () {
    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 0
    });
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'item has no quantity';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if payload has non-numeric quantity', function () {
    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: "test"
    });
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'item has no quantity';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if payload has negative quantity', function () {
    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: -1
    });
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'quantity provided must be greater than 0';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if nk.storageWrite returns null', function () {
    (mockNkStorageWrite as jest.Mock).mockReturnValueOnce(null);

    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'error saving inventory';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns failure if nk.storageWrite returns an empty array', function () {
    (mockNkStorageWrite as jest.Mock).mockReturnValueOnce([]);

    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });
    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);
    const expectedError = 'error saving inventory';

    expect(resultPayload.success).toBe(false);
    expect(resultPayload.error).toBe(expectedError);
    expect(mockLoggerError).toBeCalledWith(expectedError);
  });

  test('returns sucess if nk.storageWrite returns an ack', function () {
    (mockNkStorageWrite as jest.Mock).mockReturnValueOnce([mockStorageWriteAck]);

    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });

    const result = AddItemRpc(mockCtx, mockLogger, mockNk, payload);
    const resultPayload = JSON.parse(result);

    expect(resultPayload.success).toBe(true);
    expect(resultPayload.error).toBe(undefined);
    expect(mockLoggerError).toBeCalledTimes(0);
  });

  test('calls nk.storageRead with correct arguments', function () {
    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });
    AddItemRpc(mockCtx, mockLogger, mockNk, payload);

    expect(mockNkStorageRead).toBeCalledWith([{
      collection: "player",
      key: "inventory",
      userId: mockCtx.userId
    }]);
  });

  test('calls nk.storageWrite with just the new item when no item already exists in inventory', function () {
    (mockNkStorageRead as jest.Mock).mockReturnValueOnce({});

    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });
    AddItemRpc(mockCtx, mockLogger, mockNk, payload);

    expect(mockNkStorageWrite).toBeCalledWith([{
      collection: "player",
      key: "inventory",
      userId: mockCtx.userId,
      permissionRead: 1,
      permissionWrite: 1,
      value: {
        'Diamond Pickaxe': 1
      }
    }]);
  });

  test('calls nk.storageWrite with incremented item quantity when item already exists in inventory', function () {
    (mockNkStorageRead as jest.Mock).mockReturnValueOnce([
      {
        value: {
          'Diamond Pickaxe': 3
        }
      }
    ]);

    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });
    AddItemRpc(mockCtx, mockLogger, mockNk, payload);

    expect(mockNkStorageWrite).toBeCalledWith([{
      collection: "player",
      key: "inventory",
      userId: mockCtx.userId,
      permissionRead: 1,
      permissionWrite: 1,
      value: {
        'Diamond Pickaxe': 4
      }
    }]);
  });

  test('calls nk.storageWrite with incremented item quantity and other items when item already exists in inventory', function () {
    (mockNkStorageRead as jest.Mock).mockReturnValueOnce([
      {
        value: {
          'Diamond Pickaxe': 3,
          'Iron Sword': 1,
          'Coal': 64
        }
      }
    ]);

    const payload = JSON.stringify({
      name: 'Diamond Pickaxe',
      quantity: 1
    });
    AddItemRpc(mockCtx, mockLogger, mockNk, payload);

    expect(mockNkStorageWrite).toBeCalledWith([{
      collection: "player",
      key: "inventory",
      userId: mockCtx.userId,
      permissionRead: 1,
      permissionWrite: 1,
      value: {
        'Diamond Pickaxe': 4,
        'Iron Sword': 1,
        'Coal': 64
      }
    }]);
  });
});