您可以添加自定义匹配器。
1. 自定义匹配器
import { CsrfError } from '../src/shield';
declare global {
namespace jest {
interface Matchers<R> {
toThrowCsrfError(expected: {
statusCode: number;
message: string;
}): CustomMatcherResult;
}
}
}
const mismatchResult = (message: string) => ({
pass: false,
message: () => message,
});
expect.extend({
toThrowCsrfError(received, expected): jest.CustomMatcherResult {
try {
received();
} catch (error) {
const isCsrfError = error instanceof CsrfError;
if (!isCsrfError) {
return mismatchResult('Not an CsrfError Error');
}
if (error.message !== expected.message) {
return mismatchResult(
`Recieved Message "${error.message}" different from expected "${expected.message}"`
);
}
if (error.statusCode !== expected.statusCode) {
return mismatchResult(
`Recieved statusCode "${error.statusCode}" different from expected "${expected.statusCode}"`
);
}
return {
pass: true,
message: () => ``,
};
}
return {
pass: false,
message: () => `Expected to throw, but didn't`,
};
},
});
2. 添加到 setupFilesAfterEnv
在您jest.config
将上面的文件添加到您的setupFilesAfterEnv
列表中,例如:
const config = {
setupFilesAfterEnv: ['./test/matchers.ts'],
};
module.exports = config;
3. 打电话
expect(() => {
shield({ pathname: 'https://example.com/' });
}).toThrowCsrfError({ statusCode: 401, message: 'No CSRF cookie.' });