针对REST API多可能响应的测试(基于Frisby 2)
Great question! Since you’ve already seen Frisby 2 uses regular expressions for assertions (like the Content-Type example you shared), you can use that exact approach to match either of your two valid HTTP status codes. Here are two straightforward ways to implement this:
1. Use a Regular Expression (Simplest Approach)
Frisby’s expect('status') method accepts a regex pattern, which you can tailor to match only your allowed status codes. For example, if your valid codes are 200 and 201, use a regex that strictly matches either value:
it('should accept either 200 or 201 as valid status codes', function(doneFn) { // Set up mocks or target your API endpoint here frisby.fetch('https://your-api-url.com/target-resource') // Regex ensures exact match of either 200 or 201 .expect('status', /^(200|201)$/) .done(doneFn); });
The regex ^(200|201)$ works because:
^anchors the match to the start of the status code string$anchors the match to the end, ensuring no extra characters are present (so partial matches like2000won’t pass)(200|201)defines a group that matches either of your two valid status codes
Just replace 200 and 201 with your actual valid status codes, and this will validate that the API returns one of the two allowed values.
2. Custom Assertion (For More Flexibility)
If you need extra logic (like running different checks based on which status code is returned), you can use a custom assertion in the then chain:
it('should validate against allowed status codes', function(doneFn) { const allowedStatuses = [200, 201]; // Replace with your valid codes frisby.fetch('https://your-api-url.com/target-resource') .then(function(response) { if (!allowedStatuses.includes(response.status)) { throw new Error(`Invalid status code: ${response.status}. Expected one of ${allowedStatuses}`); } // Optional: Add status-specific validation here if (response.status === 200) { // Example: Check response body for 200 OK scenario expect(response.json).toHaveProperty('data'); } else if (response.status === 201) { // Example: Check location header for 201 Created scenario expect(response.headers.get('Location')).toBeDefined(); } }) .done(doneFn); });
This approach gives you more control if your API behaves differently depending on the status code, while still enforcing that only valid codes are accepted.
内容的提问来源于stack exchange,提问作者MatthewD

